package com.ztgf.order.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.commodity.models.dto.BrandInfoDTO;
import com.ztgf.commodity.models.dto.CommodityInfoDTO;
import com.ztgf.commodity.models.service.IBrandInfoService;
import com.ztgf.commodity.models.service.ICommodityInfoService;
import com.ztgf.commodity.models.vo.CommodityEsVO;
import com.ztgf.common.bo.HeadParamsBO;
import com.ztgf.common.constant.CommonParameter;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.CustomizeUtil;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.common.utils.StrUtils;
import com.ztgf.db.utils.RedisUtil;
import com.ztgf.dubbo.exception.ServiceException;
import com.ztgf.message.model.bo.MessageAnnouncementSaveBO;
import com.ztgf.message.model.constant.MessageTopicType;
import com.ztgf.message.model.dto.ResponseDTO;
import com.ztgf.message.model.enums.MessageEnum;
import com.ztgf.message.model.service.IKafkaProducerService;
import com.ztgf.order.common.config.YmlConfig;
import com.ztgf.order.constant.OrderConstant;
import com.ztgf.order.mapper.OrderInfoMapper;
import com.ztgf.order.models.bo.*;
import com.ztgf.order.models.bo.pay.PayOrderSaveBO;
import com.ztgf.order.models.constant.OrderExpireTimeConstant;
import com.ztgf.order.models.dto.*;
import com.ztgf.order.models.dto.pay.PayOrderLogDTO;
import com.ztgf.order.models.dto.purchase.PurchaseCommodityBargainDTO;
import com.ztgf.order.models.dto.purchase.PurchaseCommodityDTO;
import com.ztgf.order.models.dto.purchase.PurchaseInfoDTO;
import com.ztgf.order.models.enums.BargainStateEnum;
import com.ztgf.order.models.enums.OrderStateEnum;
import com.ztgf.order.models.service.*;
import com.ztgf.order.models.service.async.IAsyncOrderService;
import com.ztgf.order.models.service.pay.IPayOrderLogService;
import com.ztgf.order.models.service.pay.IPayService;
import com.ztgf.order.models.service.purchase.IPurchaseCommodityBargainService;
import com.ztgf.order.models.service.purchase.IPurchaseCommodityService;
import com.ztgf.order.models.service.purchase.IPurchaseInfoService;
import com.ztgf.order.models.vo.*;
import com.ztgf.pay.models.bo.PayBatchPrintBO;
import com.ztgf.pay.models.bo.PayOrderMotherSaveBO;
import com.ztgf.pay.models.dto.PayOrderDTO;
import com.ztgf.pay.models.dto.PayOrderMotherDTO;
import com.ztgf.pay.models.service.IPayOrderRepayService;
import com.ztgf.pay.models.service.IPayOrderService;
import com.ztgf.pay.models.vo.PayBalanceExpotVO;
import com.ztgf.pay.models.vo.PayBatchPrintVO;
import com.ztgf.search.models.dto.EsGoodsDTO;
import com.ztgf.search.models.service.ElasticsearchService;
import com.ztgf.shopping.models.bo.shop.ShopQiyuesuoAuthStateInfoBO;
import com.ztgf.shopping.models.dto.shop.ShopAddressDTO;
import com.ztgf.shopping.models.dto.shop.ShopContractParamRelationDTO;
import com.ztgf.shopping.models.dto.shop.ShopInfoDTO;
import com.ztgf.shopping.models.dto.template.ContractTempletDTO;
import com.ztgf.shopping.models.service.shop.*;
import com.ztgf.shopping.models.service.template.IContractTempletService;
import com.ztgf.shopping.models.vo.shop.ShopInfoVO;
import com.ztgf.sms.models.bo.SmsInfoSaveBO;
import com.ztgf.sms.models.service.ISmsInfoService;
import com.ztgf.sys.models.dto.SysAreaDTO;
import com.ztgf.sys.models.dto.SysDictDTO;
import com.ztgf.sys.models.dto.SysUserDTO;
import com.ztgf.sys.models.service.ISysAreaService;
import com.ztgf.sys.models.service.ISysDictService;
import com.ztgf.user.models.service.IUserLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.ztgf.common.utils.UtilConstants.isNull;

/**
 * 订单表控制器
 *
 * @author chenyu.wang
 * @Date 2020-06-03 15:32:26
 */
@Slf4j
@DubboService
@Lazy
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfoDTO> implements IOrderInfoService {

    @Resource
    private YmlConfig ymlConfig;

    @DubboReference
    private IShopAddressService shopAddressService;

    @Autowired
    private IOrderCommodityService orderCommodityService;

    @Autowired
    private IOrderCommodityRelationService orderCommodityRelationService;

    @Autowired
    private IOrderPayRelationService orderPayRelationService;

    @Autowired
    @Lazy
    private IOrderStatusService orderStatusService;

    @DubboReference
    private ISysAreaService sysAreaService;

    @DubboReference
    private IShopQiyuesuoInfoService shopQiyuesuoInfoService;

    @Autowired
    @Lazy
    private IOrderContractRelationService orderContractRelationService;

    @DubboReference
    private IKafkaProducerService kafkaProducerService;

    @Autowired
    private IOrderRightsProtectionService orderRightsProtectionService;

    @DubboReference
    private IContractTempletService contractTempletService;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private IOrderExpirationDateService orderExpirationDateService;

    @Autowired
    private IOrderInvoiceService orderInvoiceService;

    @DubboReference
    private ISysDictService sysDictService;

    @Autowired
    private IOrderProcessLogService orderProcessLogService;

    @Autowired
    @Lazy
    private IOrderContractParamRelationService orderContractParamRelationService;

    @DubboReference
    private IShopContractParamRelationService shopContractParamRelationService;

    @Autowired
    private IOrderReturnCommodityService orderReturnCommodityService;

    @DubboReference
    @Lazy
    private IPayOrderService payOrderService;

    @DubboReference
    private IBrandInfoService brandInfoService;

    @DubboReference
    @Lazy
    private IPayOrderRepayService payOrderRepayService;

    @DubboReference
    private IShopInfoService shopInfoService;

    @DubboReference
    private IUserLoginService userLoginService;

    @DubboReference
    private ICommodityInfoService commodityInfoService;

    @DubboReference
    private ISmsInfoService smsInfoService;

    @DubboReference
    private IShopQualificationService shopQualificationService;

    @Autowired
    private IPurchaseCommodityBargainService purchaseCommodityBargainService;

    @Autowired
    private IPurchaseInfoService purchaseInfoService;

    @Autowired
    private IPurchaseCommodityService purchaseCommodityService;

    @Autowired
    private IPayService payService;


    @Autowired
    private RedisUtil redisUtil;

    @DubboReference
    private ElasticsearchService elasticsearchService;

    @Autowired
    private IOrderContractEnclosureService orderContractEnclosureService;

    @Autowired
    private IOrderTimeRecordService orderTimeRecordService;

    @DubboReference
    @Lazy
    private IPayOrderLogService payOrderLogService;

    @Autowired
    private IOrderShipService orderShipService;


    @Autowired
    @Lazy
    private IOrderPaymentTypeService orderPaymentTypeService;

    @Autowired
    @Lazy
    private IOrderPaymentScaleService orderPaymentScaleService;
    @Autowired
    @Lazy
    private IAsyncOrderService asyncOrderService;


    public static final String SURE_PAY_BILL = "您编号为%s的订单线下付款凭证被商家拒绝，请联系商家或重新支付。";

    @Value(value = "${goods.url}")
    private String GOODS_URL;

    public OrderInfoDTO getByOrderNo(String orderNo) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("order_no", orderNo);
        return selectOne(wrapper);
    }

    /**
     * 根据卖家店铺id获取在这家店的所有买家店铺id
     *
     * @param sellerShopId
     * @return
     */
    @Override
    public List<Long> getListBuyerIdBySellerShopId(Long sellerShopId) {
        List<Long> buyerShopIdList = baseMapper.getListBuyerIdBySellerShopId(sellerShopId);
        if (null == buyerShopIdList) {
            return new ArrayList<Long>();
        }
        return buyerShopIdList;
    }

    /**
     * 提交订单页面的数据
     *
     * @param shopCartDataBO
     * @return
     */
    @Transactional
    @Override
    public Result<ShopCartDataVO> getShopCardData(ShopCartDataBO shopCartDataBO) {
        ShopCartDataVO shopCartDataVO = new ShopCartDataVO();
        BeanUtils.copyProperties(shopCartDataBO, shopCartDataVO);
        boolean flag = false;//是否有询盘商品
        int shopNum = 0;
        Result<ShopCartDataVO> result = new Result<>();
        BigDecimal num = new BigDecimal("0");
        BigDecimal shopAllPrice = new BigDecimal("0");
        BigDecimal totalPrice = new BigDecimal("0");
        BigDecimal purchaseFeeMoneyScalePriceTotal = new BigDecimal("0");//询盘商品总计服务费
        BigDecimal purchaseFeeMoneyScalePriceNumTotal = new BigDecimal("0");//多询盘商品总计服务费
        //付款类型(普通和分期)
        int payType = 0;
        //店铺信息
        List<ShopCardShopInfoVO> shopCardShopInfoVOList = new ArrayList<>();//存取的店铺信息
        List<ShopCardShopInfoBO> shopCardShopInfoBOList = shopCartDataBO.getShopCardShopInfoBOList();
        //收货地址
        List<ShopAddressDTO> buyerAddress = new ArrayList<ShopAddressDTO>();
        ShopAddressDTO shopAddressDTO = new ShopAddressDTO();
//        //询盘商品随机取一个地址信息(只要有一个询盘商品，则取询盘商品的地址)
//        for (ShopCardShopInfoBO shopCardShopInfoBO : shopCardShopInfoBOList) {
//            if(shopCardShopInfoBO.getPurchaseCommodityType() == BargainStateEnum.PURCHASE_COMMODITY_OK.getCode()){
//                shopAddressDTO.setAddress(purchaseCommodityDTO.getReceiveAddress());
//                shopAddressDTO.setShopId(buyerShopId);
//                shopAddressDTO.setName(purchaseCommodityDTO.getReceiveName());
//                shopAddressDTO.setMobile(purchaseCommodityDTO.getReceiveMobile());
//                shopAddressDTO.setAreaId(purchaseCommodityDTO.getReceiveAreaId());
//                break;
//            }
//        }

        int type = 0;
        for (ShopCardShopInfoBO shopCardShopInfoBO : shopCardShopInfoBOList) {
            Long shopId = shopCardShopInfoBO.getShopId();
            ShopInfoDTO shopInfoDTO = shopInfoService.selectById(shopId);
            boolean b = shopInfoService.checkShopIsClose(shopId);
            if (!b) {
                return new Result<>(CodeEnum.SHOP_FREEZE);
            }
            ShopCardShopInfoVO shopCardShopInfoVO = new ShopCardShopInfoVO();
            shopCardShopInfoVO.setShopId(shopId);
            shopCardShopInfoVO.setShopPayType(shopInfoDTO.getShopPayType());
            List<ShopCardCommodityVO> shopCardCommodityVOList = new ArrayList<>();//存取的商品信息
            for (ShopCardCommodityBO shopCardCommodityBO : shopCardShopInfoBO.getShopCardCommodityBOList()) {//店铺所属商品
                ShopCardCommodityVO shopCardCommodityVO = new ShopCardCommodityVO();
                BeanUtils.copyProperties(shopCardCommodityBO, shopCardCommodityVO);
                //询盘商品
                if(null != shopCardCommodityBO.getPurchaseCommodityType() && (shopCardCommodityBO.getPurchaseCommodityType() == BargainStateEnum.PURCHASE_COMMODITY_OK.getCode())){
                    PurchaseCommodityBargainDTO bargainDTO = purchaseCommodityBargainService.selectById(shopCardCommodityBO.getPurchaseCommodityBargainId());
                    PurchaseCommodityDTO purchaseCommodityDTO = purchaseCommodityService.selectById(bargainDTO.getPurchaseCommodityId());
                    shopAddressDTO.setAddress(purchaseCommodityDTO.getReceiveAddress());
                    shopAddressDTO.setShopId(shopId);//买家店铺id
                    shopAddressDTO.setName(purchaseCommodityDTO.getReceiveName());
                    shopAddressDTO.setMobile(purchaseCommodityDTO.getReceiveMobile());
                    shopAddressDTO.setAreaId(purchaseCommodityDTO.getReceiveAreaId());

                    BigDecimal price = bargainDTO.getPrice();
                    num = new BigDecimal(bargainDTO.getNum());
                    purchaseFeeMoneyScalePriceTotal = bargainDTO.getPurchaseFeeMoneyScalePrice().multiply(num);
                    if(bargainDTO.getPurchaseFeeMoneyScalePrice().compareTo(BigDecimal.ZERO) != 0) {
                        if (bargainDTO.getPurchaseFeeMoneyScalePayPriceStatus() == 2) {//判断询盘商品第一次是否已支付服务费
                            purchaseFeeMoneyScalePriceTotal = BigDecimal.ZERO;
                        } else {
                            Wrapper<OrderCommodityRelationDTO> wrapper = new EntityWrapper<>();
                            wrapper.eq("purchase_commodity_bargain_id", bargainDTO.getId());
                            List<OrderCommodityRelationDTO> orderCommodityRelationList = orderCommodityRelationService.selectList(wrapper);
                            if (CustomizeUtil.listIsNotNull(orderCommodityRelationList)) {
                                for (OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationList) {
                                    OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderCommodityRelationDTO.getOrderId());
                                    if (orderStatusDTO.getOrderState() == 6 || orderStatusDTO.getOrderState() == 7) {
                                        purchaseFeeMoneyScalePriceTotal = purchaseFeeMoneyScalePriceTotal;
                                    } else {
                                        result.setCode(CodeEnum.SHOP_COMMODITY_ORDER_ERROR.getCode());
                                        result.setMsg(CodeEnum.SHOP_COMMODITY_ORDER_ERROR.getMsg());//返回该商品已存在未完成订单
                                        return result;
                                    }
                                }
                            } else {
                                purchaseFeeMoneyScalePriceTotal = purchaseFeeMoneyScalePriceTotal;
                            }
                        }
                    }
                    //设置订单商品信息
                    OrderCommodityVO orderCommodityVO = new OrderCommodityVO();
                    orderCommodityVO.setGoodsName(bargainDTO.getCommodityName());
                    orderCommodityVO.setLogoUrl(bargainDTO.getCommodityLogoUrl());
                    orderCommodityVO.setCommodityId(bargainDTO.getPurchaseCommodityId());//商品id
                    orderCommodityVO.setPrice(bargainDTO.getPrice());
                    orderCommodityVO.setAvailableArea("0");//全国发货
                    orderCommodityVO.setPurchaseFeeMoneyScalePrice(purchaseFeeMoneyScalePriceTotal);//询盘商品服务费(单服务费乘以数量)

                    purchaseFeeMoneyScalePriceNumTotal = purchaseFeeMoneyScalePriceNumTotal.add(purchaseFeeMoneyScalePriceTotal);

                    orderCommodityVO.setPurchaseCommodityOnePrice(bargainDTO.getOnePrice());//一次报价
                    orderCommodityVO.setPurchaseCommodityTwoPrice(bargainDTO.getTwoPrice());//二次报价
                    orderCommodityVO.setPurchaseCommodityThreePrice(bargainDTO.getThreePrice());//三次报价
                    orderCommodityVO.setPurchasePlatBargainStatus(bargainDTO.getPlatBargainStatus());//砍价状态
                    orderCommodityVO.setPurchaseCommodityBargainId(bargainDTO.getId());//询盘商品报价表id
                    orderCommodityVO.setSendDays(bargainDTO.getSendDays());//预计发货时间
                    orderCommodityVO.setPurchaseCommodityType(1);
                    orderCommodityVO.setFirstBalance(bargainDTO.getFristScale().intValue());//首款比例
                    orderCommodityVO.setTailBalance(bargainDTO.getFinalScale().intValue());//尾款比例

                    orderCommodityVO.setOneBargainPrice(bargainDTO.getOneBargainPrice());//卖家第一次议价

                    //店铺商品信息
                    shopCardCommodityVO.setCommodityDiscounts(orderCommodityVO);//设置商品信息
                    totalPrice = price.multiply(num);
                    shopCardCommodityVO.setCommodityNum(bargainDTO.getNum().toString());
                    shopCardCommodityVO.setCommodityId(bargainDTO.getPurchaseCommodityId());
                    shopCardCommodityVO.setCommodityImgUrl(bargainDTO.getCommodityLogoUrl());//商品图片
                    shopCardCommodityVO.setCommodityName(bargainDTO.getCommodityName());//商品名字
                    shopCardCommodityVO.setSingleCommodityPrice(price);//单价
                    shopCardCommodityVO.setCommodityTotal(totalPrice);//小计
                    shopCardCommodityVO.setPurchaseFeeMoneyScalePrice(purchaseFeeMoneyScalePriceTotal);//询盘商品服务费(单服务费乘以数量)
                    shopCardCommodityVO.setCommodityRealTotal(totalPrice.add(purchaseFeeMoneyScalePriceTotal));//商品真实价格
                    shopCardCommodityVOList.add(shopCardCommodityVO);
                    //获取商品类型(默认 0现货 1预售)
                    payType = bargainDTO.getCommodityType();

                    //店铺信息
                    shopCardShopInfoVO.setShopId(bargainDTO.getShopId());
                    shopCardShopInfoVO.setShopPayType(shopInfoDTO.getShopPayType());
                    shopCardShopInfoVO.setPurchaseCommodityType(1);//询盘类型
                    if(!flag){
                        flag = true;
                    }
                }else {

                    OrderCommodityAttrBO orderCommodityAttrBO = new OrderCommodityAttrBO();
                    orderCommodityAttrBO.setCommodityId(shopCardCommodityBO.getCommodityId());
                    orderCommodityAttrBO.setAtrrIds(shopCardCommodityBO.getAttrIds());
                    orderCommodityAttrBO.setBuyersId(shopCartDataBO.getBuyerShopId());
                    OrderCommodityVO orderCommodityVO = orderCommodityService.queryGoodsPrice(orderCommodityAttrBO);
                    shopCardCommodityVO.setCommodityDiscounts(orderCommodityVO);//设置商品优惠信息

                    BigDecimal price = orderCommodityVO.getPrice();
                    num = new BigDecimal(shopCardCommodityVO.getCommodityNum());
                    totalPrice = price.multiply(num);
                    shopCardCommodityVO.setCommodityImgUrl(orderCommodityVO.getLogoUrl());//商品图片
                    shopCardCommodityVO.setCommodityName(orderCommodityVO.getGoodsName());//商品名字
                    shopCardCommodityVO.setSingleCommodityPrice(price);//单价
                    shopCardCommodityVO.setCommodityTotal(totalPrice);//小计
                    shopCardCommodityVO.setCommodityRealTotal(totalPrice);//商品真实价格
                    // 获取商品是否询价
                    CommodityInfoDTO commodityInfoDTO = commodityInfoService.selectById(shopCardCommodityBO.getCommodityId());
                    Integer isInquiry = commodityInfoDTO.getIsInquiry();
                    shopCardCommodityVO.setIsInquiry(isInquiry);
                    if (isInquiry.equals(1)) {
                        type = 1;
                    }
                    shopCardCommodityVOList.add(shopCardCommodityVO);
                }
                shopAllPrice = shopAllPrice.add(totalPrice);
                shopNum += num.intValue();//商品数量
            }
            shopCardShopInfoVO.setShopCardCommodityVOList(shopCardCommodityVOList);
            shopCardShopInfoVOList.add(shopCardShopInfoVO);
        }
        //金额计算

        if(flag == true){
            shopCartDataVO.setShopAddressDTO(shopAddressDTO);
        }else{
            buyerAddress = shopAddressService.getAllBuyerAddress(shopCartDataBO.getBuyerShopId());
            if (buyerAddress.size() > 0) {
                shopCartDataVO.setShopAddressDTO(buyerAddress.get(0));
            }
        }
        shopCartDataVO.setShopCardShopInfoVOList(shopCardShopInfoVOList);
        shopCartDataVO.setShopAllNum(shopNum);//商品总数量
        shopCartDataVO.setShopAllPrice(shopAllPrice);//商品总价格
        shopCartDataVO.setShopDiscounts(new BigDecimal("0"));//商品优惠
        shopCartDataVO.setFreight("0");//运费
        shopCartDataVO.setPurchaseCommodityType(1);//询盘商品类型
        shopCartDataVO.setLastPrice(shopAllPrice);//商品实付
        shopCartDataVO.setPurchaseFeeMoneyScalePriceTotal(purchaseFeeMoneyScalePriceNumTotal);//询盘商品总计服务费
        shopCartDataVO.setType(type);//只要有询价就是询价
        //shopCartDataVO.setShopAddressDTO(shopAddressDTO);
        //shopCartDataVO.setPayType(bargainDTO.getCommodityType());
        return new Result<>(shopCartDataVO);
    }

    /**
     * 提交订单页面的数据
     *
     * @param shopCartDataBO
     * @return
     */
    public Result<ShopCartDataVO> getShopCardData_bak(ShopCartDataBO shopCartDataBO) {
        ShopCartDataVO shopCartDataVO = new ShopCartDataVO();
        BeanUtils.copyProperties(shopCartDataBO, shopCartDataVO);
        //收货地址
        List<ShopAddressDTO> buyerAddress = shopAddressService.getAllBuyerAddress(shopCartDataBO.getBuyerShopId());
        if (buyerAddress.size() > 0) {
            shopCartDataVO.setShopAddressDTO(buyerAddress.get(0));
        }
        int shopNum = 0;
        BigDecimal shopAllPrice = new BigDecimal("0");
        //店铺信息
        List<ShopCardShopInfoVO> shopCardShopInfoVOList = new ArrayList<>();//存取的店铺信息
        List<ShopCardShopInfoBO> shopCardShopInfoBOList = shopCartDataBO.getShopCardShopInfoBOList();
        int type = 0;
        for (ShopCardShopInfoBO shopCardShopInfoBO : shopCardShopInfoBOList) {
            Long shopId = shopCardShopInfoBO.getShopId();
            ShopInfoDTO shopInfoDTO = shopInfoService.selectById(shopId);
            boolean b = shopInfoService.checkShopIsClose(shopId);
            if (!b) {
                return new Result<>(CodeEnum.SHOP_FREEZE);
            }
            ShopCardShopInfoVO shopCardShopInfoVO = new ShopCardShopInfoVO();
            shopCardShopInfoVO.setShopId(shopId);
            shopCardShopInfoVO.setShopPayType(shopInfoDTO.getShopPayType());
            List<ShopCardCommodityVO> shopCardCommodityVOList = new ArrayList<>();//存取的商品信息
            for (ShopCardCommodityBO shopCardCommodityBO : shopCardShopInfoBO.getShopCardCommodityBOList()) {//店铺所属商品
                ShopCardCommodityVO shopCardCommodityVO = new ShopCardCommodityVO();
                BeanUtils.copyProperties(shopCardCommodityBO, shopCardCommodityVO);
                OrderCommodityAttrBO orderCommodityAttrBO = new OrderCommodityAttrBO();
                orderCommodityAttrBO.setCommodityId(shopCardCommodityBO.getCommodityId());
                orderCommodityAttrBO.setAtrrIds(shopCardCommodityBO.getAttrIds());
                orderCommodityAttrBO.setBuyersId(shopCartDataBO.getBuyerShopId());
                OrderCommodityVO orderCommodityVO = orderCommodityService.queryGoodsPrice(orderCommodityAttrBO);
                shopCardCommodityVO.setCommodityDiscounts(orderCommodityVO);//设置商品优惠信息

                BigDecimal price = orderCommodityVO.getPrice();
                BigDecimal num = new BigDecimal(shopCardCommodityVO.getCommodityNum());
                BigDecimal totalPrice = price.multiply(num);
                shopCardCommodityVO.setCommodityImgUrl(orderCommodityVO.getLogoUrl());//商品图片
                shopCardCommodityVO.setCommodityName(orderCommodityVO.getGoodsName());//商品名字
                shopCardCommodityVO.setSingleCommodityPrice(price);//单价
                shopCardCommodityVO.setCommodityTotal(totalPrice);//小计
                shopCardCommodityVO.setCommodityRealTotal(totalPrice);//商品真实价格
                // 获取商品是否询价
                CommodityInfoDTO commodityInfoDTO = commodityInfoService.selectById(shopCardCommodityBO.getCommodityId());
                Integer isInquiry = commodityInfoDTO.getIsInquiry();
                shopCardCommodityVO.setIsInquiry(isInquiry);
                if (isInquiry.equals(1)) {
                    type = 1;
                }
                shopCardCommodityVOList.add(shopCardCommodityVO);

                shopAllPrice = shopAllPrice.add(totalPrice);
                shopNum += num.intValue();//商品数量
            }
            shopCardShopInfoVO.setShopCardCommodityVOList(shopCardCommodityVOList);
            shopCardShopInfoVOList.add(shopCardShopInfoVO);
        }
        //金额计算
        shopCartDataVO.setShopCardShopInfoVOList(shopCardShopInfoVOList);
        shopCartDataVO.setShopAllNum(shopNum);//商品总数量
        shopCartDataVO.setShopAllPrice(shopAllPrice);//商品总价格
        shopCartDataVO.setShopDiscounts(new BigDecimal("0"));//商品优惠
        shopCartDataVO.setFreight("0");//运费
        shopCartDataVO.setLastPrice(shopAllPrice);//商品实付
        shopCartDataVO.setType(type);
        return new Result<>(shopCartDataVO);
    }


    /**
     * 提交订单页面的数据
     *
     * @param purchaseCommodityBargainId,buyerShopId
     * @return
     */
    @Transactional
    @Override
    public Result<ShopCartDataVO> getShopCardDataForPurchaseInfo(Long purchaseCommodityBargainId,Long buyerShopId) {
        ShopCartDataVO shopCartDataVO = new ShopCartDataVO();
        int shopNum = 0;
        BigDecimal shopAllPrice = new BigDecimal("0");
        BigDecimal purchaseFeeMoneyScaleTotal = new BigDecimal("0");
        Result<ShopCartDataVO> result = new Result<>();
        PurchaseCommodityBargainDTO bargainDTO = purchaseCommodityBargainService.selectById(purchaseCommodityBargainId);
        PurchaseCommodityDTO purchaseCommodityDTO = purchaseCommodityService.selectById(bargainDTO.getPurchaseCommodityId());
        BigDecimal price = bargainDTO.getPrice();
        BigDecimal num = new BigDecimal(bargainDTO.getNum());
        BigDecimal purchaseFeeMoneyScalePriceTotal = bargainDTO.getPurchaseFeeMoneyScalePrice().multiply(num);

        if(bargainDTO.getPurchaseFeeMoneyScalePrice().compareTo(BigDecimal.ZERO) != 0) {
            if (bargainDTO.getPurchaseFeeMoneyScalePayPriceStatus() == 2) {//判断询盘商品第一次是否已支付服务费
                purchaseFeeMoneyScalePriceTotal = BigDecimal.ZERO;
            } else {
                Wrapper<OrderCommodityRelationDTO> wrapper = new EntityWrapper<>();
                wrapper.eq("purchase_commodity_bargain_id", bargainDTO.getId());
                List<OrderCommodityRelationDTO> orderCommodityRelationList = orderCommodityRelationService.selectList(wrapper);
                if (CustomizeUtil.listIsNotNull(orderCommodityRelationList)) {
                    for (OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationList) {
                        OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderCommodityRelationDTO.getOrderId());
                        if (orderStatusDTO.getOrderState() == 6 || orderStatusDTO.getOrderState() == 7) {
                            purchaseFeeMoneyScalePriceTotal = purchaseFeeMoneyScalePriceTotal;
                        } else {
                            result.setCode(CodeEnum.SHOP_COMMODITY_ORDER_ERROR.getCode());
                            result.setMsg(CodeEnum.SHOP_COMMODITY_ORDER_ERROR.getMsg());//返回该商品已存在未完成订单
                            return result;
                        }
                    }
                } else {
                    purchaseFeeMoneyScalePriceTotal = purchaseFeeMoneyScalePriceTotal;
                }
            }
        }

        //设置订单商品信息
        OrderCommodityVO orderCommodityVO = new OrderCommodityVO();
        orderCommodityVO.setGoodsName(bargainDTO.getCommodityName());
        orderCommodityVO.setLogoUrl(bargainDTO.getCommodityLogoUrl());
        orderCommodityVO.setCommodityId(bargainDTO.getPurchaseCommodityId());//询盘商品表id
        orderCommodityVO.setPrice(bargainDTO.getPrice());
        orderCommodityVO.setAvailableArea("0");//全国发货
        orderCommodityVO.setPurchaseFeeMoneyScalePrice(purchaseFeeMoneyScalePriceTotal);//询盘商品服务费(单服务费乘以数量)

        orderCommodityVO.setPurchaseCommodityOnePrice(bargainDTO.getOnePrice());//一次报价
        orderCommodityVO.setPurchaseCommodityTwoPrice(bargainDTO.getTwoPrice());//二次报价
        orderCommodityVO.setPurchaseCommodityThreePrice(bargainDTO.getThreePrice());//三次报价
        orderCommodityVO.setPurchasePlatBargainStatus(bargainDTO.getPlatBargainStatus());//砍价状态
        orderCommodityVO.setPurchaseCommodityBargainId(purchaseCommodityBargainId);//询盘商品报价表id
        orderCommodityVO.setSendDays(bargainDTO.getSendDays());//预计发货时间
        orderCommodityVO.setPurchaseCommodityType(1);
        orderCommodityVO.setFirstBalance(bargainDTO.getFristScale().intValue());//首款比例
        orderCommodityVO.setTailBalance(bargainDTO.getFinalScale().intValue());//尾款比例

        orderCommodityVO.setOneBargainPrice(bargainDTO.getOneBargainPrice());//卖家第一次议价

        //店铺商品信息
        ShopCardCommodityVO shopCardCommodityVO = new ShopCardCommodityVO();
        shopCardCommodityVO.setCommodityDiscounts(orderCommodityVO);//设置商品信息
        BigDecimal totalPrice = price.multiply(num);
        shopCardCommodityVO.setCommodityNum(bargainDTO.getNum().toString());
        shopCardCommodityVO.setCommodityId(bargainDTO.getPurchaseCommodityId());
        shopCardCommodityVO.setCommodityImgUrl(bargainDTO.getCommodityLogoUrl());//商品图片
        shopCardCommodityVO.setCommodityName(bargainDTO.getCommodityName());//商品名字
        shopCardCommodityVO.setSingleCommodityPrice(price);//单价
        shopCardCommodityVO.setCommodityTotal(totalPrice);//小计
        shopCardCommodityVO.setPurchaseFeeMoneyScalePrice(purchaseFeeMoneyScalePriceTotal);//询盘商品服务费(单服务费乘以数量)
        shopCardCommodityVO.setCommodityRealTotal(totalPrice.add(purchaseFeeMoneyScalePriceTotal));//商品真实价格

        List<ShopCardCommodityVO> shopCardCommodityVOList = new ArrayList<ShopCardCommodityVO>();
        shopCardCommodityVOList.add(shopCardCommodityVO);


        //店铺信息
        ShopInfoDTO shopInfoDTO = shopInfoService.selectById(bargainDTO.getShopId());
        ShopCardShopInfoVO shopCardShopInfoVO = new ShopCardShopInfoVO();
        shopCardShopInfoVO.setShopId(bargainDTO.getShopId());
        shopCardShopInfoVO.setShopPayType(shopInfoDTO.getShopPayType());
        shopCardShopInfoVO.setPurchaseCommodityType(1);//询盘类型
        shopCardShopInfoVO.setShopCardCommodityVOList(shopCardCommodityVOList);
        List<ShopCardShopInfoVO> shopCardShopInfoVOList = new ArrayList<ShopCardShopInfoVO>();
        shopCardShopInfoVOList.add(shopCardShopInfoVO);

        //地址信息
        ShopAddressDTO shopAddressDTO = new ShopAddressDTO();
        shopAddressDTO.setAddress(purchaseCommodityDTO.getReceiveAddress());
        shopAddressDTO.setShopId(buyerShopId);
        shopAddressDTO.setName(purchaseCommodityDTO.getReceiveName());
        shopAddressDTO.setMobile(purchaseCommodityDTO.getReceiveMobile());
        shopAddressDTO.setAreaId(purchaseCommodityDTO.getReceiveAreaId());


        //金额计算
        shopCartDataVO.setShopCardShopInfoVOList(shopCardShopInfoVOList);
        shopCartDataVO.setShopAllNum(bargainDTO.getNum());//商品总数量
        shopCartDataVO.setShopAllPrice(totalPrice.add(purchaseFeeMoneyScalePriceTotal));//商品总价格
        shopCartDataVO.setShopDiscounts(new BigDecimal("0"));//商品优惠
        shopCartDataVO.setFreight("0");//运费
        shopCartDataVO.setPurchaseCommodityType(1);//询盘商品类型
        shopCartDataVO.setLastPrice(shopAllPrice);//商品实付
        shopCartDataVO.setPurchaseFeeMoneyScalePriceTotal(purchaseFeeMoneyScalePriceTotal);//询盘商品总计服务费
        shopCartDataVO.setType(0);//只有普通
        shopCartDataVO.setShopAddressDTO(shopAddressDTO);
        shopCartDataVO.setPayType(bargainDTO.getCommodityType());
        return new Result<>(shopCartDataVO);
    }

    public Result<ShopCartDataVO> getShopCardDataForPurchaseInfo3(Long purchaseCommodityBargainId,Long buyerShopId) {
        ShopCartDataVO shopCartDataVO = new ShopCartDataVO();
        int shopNum = 0;
        BigDecimal shopAllPrice = new BigDecimal("0");
        BigDecimal purchaseFeeMoneyScaleTotal = new BigDecimal("0");

        PurchaseCommodityBargainDTO bargainDTO = purchaseCommodityBargainService.selectById(purchaseCommodityBargainId);
        ShopAddressDTO shopAddressDTO = new ShopAddressDTO();
        shopAddressDTO.setAddress(bargainDTO.getSendAddress());
        shopAddressDTO.setShopId(bargainDTO.getShopId());
        shopAddressDTO.setName(bargainDTO.getSendName());
        shopAddressDTO.setMobile(bargainDTO.getSendMobile());
        shopAddressDTO.setAreaId(bargainDTO.getSendAreaId());

        shopCartDataVO.setType(0);
        shopCartDataVO.setPayType(bargainDTO.getCommodityType());
        shopCartDataVO.setShopAllNum(bargainDTO.getNum());
        shopCartDataVO.setFreight("0");
        //shopCartDataBO.setShopAllPrice(bargainDTO.getPrice());
        shopCartDataVO.setLastPrice(bargainDTO.getPrice());
        shopCartDataVO.setShopAddressDTO(shopAddressDTO);

        ShopCartDataBO shopCartDataBO = new ShopCartDataBO();
        shopCartDataBO.setBuyerShopId(buyerShopId);
        shopCartDataBO.setPayType(bargainDTO.getCommodityType());
        shopCartDataBO.setType(0);
        ShopCardCommodityBO shopCardCommodity = new ShopCardCommodityBO();
        shopCardCommodity.setCommodityId(0l);
        shopCardCommodity.setCommodityName(bargainDTO.getCommodityName());
        shopCardCommodity.setCommodityNum(bargainDTO.getNum().toString());
        shopCardCommodity.setCommodityImgUrl(bargainDTO.getCommodityLogoUrl());
        shopCardCommodity.setAttrIds("");
        List<ShopCardCommodityBO> ShopCardCommodityBOList = new ArrayList<ShopCardCommodityBO>();
        ShopCardCommodityBOList.add(shopCardCommodity);
        ShopCardShopInfoBO shopCardShopInfo = new ShopCardShopInfoBO();
        shopCardShopInfo.setShopId(bargainDTO.getShopId());
        shopCardShopInfo.setShopCardCommodityBOList(ShopCardCommodityBOList);
        shopCardShopInfo.setPurchaseCommodityType(1);//询盘商品类型标识
        List<ShopCardShopInfoBO>  shopCardShopInfoBOList= new ArrayList<ShopCardShopInfoBO>();
        shopCardShopInfoBOList.add(shopCardShopInfo);


        //店铺信息
        List<ShopCardShopInfoVO> shopCardShopInfoVOList = new ArrayList<>();//存取的店铺信息
        for (ShopCardShopInfoBO shopCardShopInfoBO : shopCardShopInfoBOList) {
            Long shopId = shopCardShopInfoBO.getShopId();
            ShopInfoDTO shopInfoDTO = shopInfoService.selectById(shopId);
            boolean b = shopInfoService.checkShopIsClose(shopId);
            if (!b) {
                return new Result<>(CodeEnum.SHOP_FREEZE);
            }
            ShopCardShopInfoVO shopCardShopInfoVO = new ShopCardShopInfoVO();
            shopCardShopInfoVO.setShopId(shopId);
            shopCardShopInfoVO.setShopPayType(shopInfoDTO.getShopPayType());
            shopCardShopInfoVO.setPurchaseCommodityType(1);//询盘商品类型
            //shopCardShopInfoVO.setPurchaseFeeMoneyScale();
            List<ShopCardCommodityVO> shopCardCommodityVOList = new ArrayList<>();//存取的商品信息
            for (ShopCardCommodityBO shopCardCommodityBO : shopCardShopInfoBO.getShopCardCommodityBOList()) {//店铺所属商品
                ShopCardCommodityVO shopCardCommodityVO = new ShopCardCommodityVO();
                BeanUtils.copyProperties(shopCardCommodityBO, shopCardCommodityVO);
                OrderCommodityAttrBO orderCommodityAttrBO = new OrderCommodityAttrBO();
                orderCommodityAttrBO.setCommodityId(shopCardCommodityBO.getCommodityId());
                orderCommodityAttrBO.setAtrrIds(shopCardCommodityBO.getAttrIds());
                orderCommodityAttrBO.setBuyersId(shopCartDataBO.getBuyerShopId());
                OrderCommodityVO orderCommodityVO = new OrderCommodityVO();
                orderCommodityVO.setGoodsName(shopCardCommodityVO.getCommodityName());
                orderCommodityVO.setLogoUrl(shopCardCommodityBO.getCommodityImgUrl());
                orderCommodityVO.setCommodityId(0L);
                orderCommodityVO.setPrice(shopCartDataVO.getLastPrice());
                orderCommodityVO.setAvailableArea(bargainDTO.getSendAreaId().toString());
                orderCommodityVO.setPurchaseFeeMoneyScalePrice(bargainDTO.getPurchaseFeeMoneyScale());//询盘商品服务费

                shopCardCommodityVO.setCommodityDiscounts(orderCommodityVO);//设置商品优惠信息
                BigDecimal price = shopCartDataVO.getLastPrice();
                BigDecimal num = new BigDecimal(shopCardCommodityVO.getCommodityNum());
                BigDecimal totalPrice = price.multiply(num);
                shopCardCommodityVO.setCommodityImgUrl(shopCardCommodityBO.getCommodityImgUrl());//商品图片
                shopCardCommodityVO.setCommodityName(shopCardCommodityBO.getCommodityName());//商品名字
                shopCardCommodityVO.setSingleCommodityPrice(price);//单价
                shopCardCommodityVO.setCommodityTotal(totalPrice);//小计
                shopCardCommodityVO.setCommodityRealTotal(totalPrice.add(bargainDTO.getPurchaseFeeMoneyScalePrice()));//商品真实价格

                shopCardCommodityVOList.add(shopCardCommodityVO);

                shopAllPrice = shopAllPrice.add(totalPrice);
                shopNum += num.intValue();//商品数量

                purchaseFeeMoneyScaleTotal = purchaseFeeMoneyScaleTotal.add(bargainDTO.getPurchaseFeeMoneyScalePrice());//计算询盘商品总价
            }
            shopCardShopInfoVO.setShopCardCommodityVOList(shopCardCommodityVOList);
            shopCardShopInfoVOList.add(shopCardShopInfoVO);
        }
        //金额计算
        shopCartDataVO.setShopCardShopInfoVOList(shopCardShopInfoVOList);
        shopCartDataVO.setShopAllNum(shopNum);//商品总数量
        shopCartDataVO.setShopAllPrice(shopAllPrice);//商品总价格
        shopCartDataVO.setShopDiscounts(new BigDecimal("0"));//商品优惠
        shopCartDataVO.setFreight("0");//运费
        shopCartDataVO.setPurchaseCommodityType(1);//询盘商品类型
        shopCartDataVO.setLastPrice(shopAllPrice);//商品实付
        shopCartDataVO.setPurchaseFeeMoneyScalePriceTotal(purchaseFeeMoneyScaleTotal);//询盘商品总计服务费
        return new Result<>(shopCartDataVO);
    }

    /**
     * 提交订单
     *
     * @param orderDataBO
     * @return
     */
    @Transactional
    @Override
    public Result<List<Long>> createOrder(OrderDataBO orderDataBO, String sessionId) {
        Long buyerId = orderDataBO.getBuyerShopId();
        //判断是否有电子签章
        ShopQiyuesuoAuthStateInfoBO byQiyuesuoState = shopQiyuesuoInfoService.getByQiyuesuoState(buyerId);
        if (!byQiyuesuoState.isAuthState()) {
            return new Result<>(CodeEnum.CONTACT_SEAL_ERROR);
        }
        //判断是否开户
        ShopInfoDTO shopInfoDTO = shopInfoService.selectById(orderDataBO.getBuyerShopId());
        if (shopInfoDTO.getCiccStatus() == 0) {
            return new Result<>(CodeEnum.FAIL_200003);
        }
        //判断买家基本资质是否过期
        boolean isExpire = shopQualificationService.getIsExpire(orderDataBO.getBuyerShopId());
        if (isExpire) {
            return new Result<>(CodeEnum.FAIL_SHOP_BASIC_CERTIFICATION_EXPIRE_3011);
        }
        HeadParamsBO headParamsBO = CommonParameter.getHeadParamsBO();
        SysUserDTO sysUserDTO = null;
        if (StrUtils.isNotEmpty(sessionId)) {
            sysUserDTO = (SysUserDTO) redisUtil.getSession(sessionId, headParamsBO.getSource() + "");//获取操作人
        }


        log.error("----------1--------------");
        //判断重复下单 暂时不要
        Result<List<Long>> result = new Result<>();
        List<OrderInfoVO> orderInfoVOList = new ArrayList<>();
        for (OrderShopInfoBO orderShopInfoBO : orderDataBO.getOrderShopInfoBOList()) {
            Long shopId = orderShopInfoBO.getShopId();
            boolean b = shopInfoService.checkShopIsClose(shopId);
            if (!b) {
                return new Result<>(CodeEnum.SHOP_FREEZE);
            }
            ShopInfoDTO sellShopInfoDTO = shopInfoService.selectById(shopId);
            log.info("卖家店铺信息:{}", sellShopInfoDTO);
            OrderInfoVO orderInfoVO = new OrderInfoVO();
            BeanUtils.copyProperties(orderDataBO, orderInfoVO);
            orderInfoVO.setSellPayType(sellShopInfoDTO.getShopPayType());
            orderInfoVO.setBuyShopId(orderDataBO.getBuyerShopId());//买家店铺id
            orderInfoVO.setSellShopId(shopId);//卖家店铺id
//            orderInfoVO.setType(orderDataBO.getType());//支付方式
            orderInfoVO.setPayType(orderDataBO.getPayType());//订单类型
            orderInfoVO.setPlaceOrderType(orderDataBO.getPlaceOrderType());//下订单类型
            //TODO 订单类型:0普通,1询价
            int type = 0;
            int purchaseOrderType = 0; //询盘订单类型 0普通  1询盘
            int shopCommodityNum = 0;//店铺下商品总数量
            BigDecimal shopTotalMoney = new BigDecimal("0");//店铺下总价
            BigDecimal shopDiscountMoney = new BigDecimal("0");//店铺下店铺优惠
            BigDecimal shopActualMoney = new BigDecimal("0");//店铺下应付总额
            BigDecimal freightMoney = new BigDecimal("0");//运费
            BigDecimal commissionMoney = new BigDecimal("0");//佣金比例
            BigDecimal purchaseFeeMoneyScalePriceTotal = new BigDecimal("0");//询盘商品砍价服务费总计
            for (OrderCommodityBO orderCommodityBO : orderShopInfoBO.getOrderCommodityBOList()) {//店铺下商品
                //判断是否为询盘商品
                if(null != orderCommodityBO.getPurchaseCommodityType() && orderCommodityBO.getPurchaseCommodityType() == BargainStateEnum.PURCHASE_COMMODITY_OK.getCode()){
                    OrderCommodityDetailVO orderCommodityDetailVO = new OrderCommodityDetailVO();
                    BeanUtils.copyProperties(orderCommodityBO, orderCommodityDetailVO);
                    //PurchaseCommodityDTO purchaseCommodityDTO = purchaseCommodityService.selectById(orderCommodityBO.getCommodityId());
                    PurchaseCommodityBargainDTO dto  = purchaseCommodityBargainService.selectById(orderCommodityBO.getPurchaseCommodityBargainId());
                    PurchaseInfoDTO purchaseInfoDTO  = purchaseInfoService.selectById(dto.getPurchaseId());//询盘单信息

                    if(purchaseInfoDTO.getPurchaseFeeMoneyStatus() == 2){//支付平台砍价报名费成功
                        orderCommodityDetailVO.setPurchaseFeeMoney(purchaseInfoDTO.getPurchaseFeeMoney());
                    }
                    orderCommodityDetailVO.setPurchaseInfoId(purchaseInfoDTO.getId());



                    //获取品牌信息
                    BrandInfoDTO brandInfoDTO = brandInfoService.selectById(dto.getBrandId());

                    OrderCommodityAttrBO orderCommodityAttrBO = new OrderCommodityAttrBO();
                    orderCommodityAttrBO.setBuyersId(buyerId);
                    orderCommodityAttrBO.setCommodityId(dto.getCommodityId());
                    orderCommodityAttrBO.setAtrrIds("");
                    OrderCommodityVO orderCommodityVO = orderCommodityService.queryGoodsPrice(orderCommodityAttrBO);//查询订单优惠
                    if(null == orderCommodityVO){
                        orderCommodityDetailVO.setCategoryId(null);
                    }else {
                        orderCommodityDetailVO.setCategoryId(orderCommodityVO.getCategoryId());
                    }
                    orderCommodityDetailVO.setSendDays(dto.getSendDays());
                    orderCommodityDetailVO.setPurchaseCommodityType(1);

                    BigDecimal price = dto.getPrice();//商品单价
                    orderCommodityDetailVO.setSingleCommodityPrice(price);//设置商品单价
                    BigDecimal singleCommodityActualMoney = new BigDecimal("0");
                    //判断该商品是否砍价成功
                    if(dto.getBargainStatus().equals(BargainStateEnum.BARGAIN_STATE_OK.getCode())){
                        singleCommodityActualMoney = price.add(dto.getPurchaseFeeMoneyScalePrice());//最新价格加上服务费（单商品实付价格）
                    }
                    orderCommodityDetailVO.setSingleCommodityRealTotal(singleCommodityActualMoney);//添加单商品实付价格

                    BigDecimal num = new BigDecimal(orderCommodityDetailVO.getCommodityNum());//商品数量
                    shopCommodityNum += num.intValue();//店铺下商品数量
                    orderCommodityDetailVO.setCommodityNum(num.toString());//添加此商品数量

                    BigDecimal totalPrice = price.multiply(num);//商品总价
                    shopTotalMoney = shopTotalMoney.add(totalPrice);//添加进店铺商品总价
                    orderCommodityDetailVO.setCommodityTotal(totalPrice);//添加此商品总价 小计

                    //shopActualMoney = shopTotalMoney.add((dto.getPurchaseFeeMoneyScalePrice().multiply(num)));//店铺应付总价
                    //orderCommodityDetailVO.setCommodityRealTotal(totalPrice.add((dto.getPurchaseFeeMoneyScalePrice().multiply(num))));//添加此商品总应付价格 实付

                    shopActualMoney = shopActualMoney.add(totalPrice);//店铺实付不需要加砍价服务费
                    orderCommodityDetailVO.setCommodityRealTotal(totalPrice);//商品实付不需要加砍价服务费

                    BigDecimal shopTotalPrice = totalPrice;//总价减去优惠总价 实付

                    BigDecimal dividend = dto.getPurchaseDividendScale();//分润比例
                    BigDecimal dividendAllPrice = shopTotalPrice.multiply(dividend).setScale(2, BigDecimal.ROUND_UP);//分润总价格
                    BigDecimal singleDividendAllPrice = singleCommodityActualMoney.multiply(dividend).setScale(2, BigDecimal.ROUND_UP);//单商品分润价格
                    orderCommodityDetailVO.setSingleCommissionMoney(singleDividendAllPrice);//设置单商品分润价格
                    orderCommodityDetailVO.setCommissionMoney(dividendAllPrice);//设置分润总价格
                    commissionMoney = commissionMoney.add(dividendAllPrice);//店铺分润总价
                    orderCommodityDetailVO.setCommissionRate(dividend);//分润比例
                    //orderCommodityDetailVO.setTaxRate(orderCommodityVO.getTaxRate());//税率
                    orderCommodityDetailVO.setUnitName(BargainStateEnum.PURCHASE_COMMODITY_UNITNAME.getMsg());//单位
                    orderCommodityDetailVO.setBrandName(null != brandInfoDTO ? brandInfoDTO.getName():BargainStateEnum.PURCHASE_COMMODITY_BRAND.getMsg());//品牌
                    orderCommodityDetailVO.setAttrName(dto.getSpecificationModel());//规格型号名字
                    orderCommodityDetailVO.setCommodityName(dto.getCommodityName());//商品名称
                    orderCommodityDetailVO.setFirstBalance(dto.getFristScale().intValue());//首期比例
                    orderCommodityDetailVO.setTailBalance(dto.getFinalScale().intValue());//末期比例
                    orderCommodityDetailVO.setWarrantyMonth(dto.getWarranty());//质保期
                    orderCommodityDetailVO.setPurchaseCommodityBargainId(dto.getId());//询盘报价表id
                    BigDecimal purchaseFeeMoneyScalePrice = dto.getPurchaseFeeMoneyScalePrice().multiply(num);//计算询盘砍价服务费
                    if(dto.getPurchaseFeeMoneyScalePrice().compareTo(BigDecimal.ZERO) != 0) {
                        if (dto.getPurchaseFeeMoneyScalePayPriceStatus() == 2) {//判断询盘商品第一次是否已支付服务费
                            purchaseFeeMoneyScalePrice = BigDecimal.ZERO;
                        } else {
                            Wrapper<OrderCommodityRelationDTO> wrapper = new EntityWrapper<>();
                            wrapper.eq("purchase_commodity_bargain_id", dto.getId());
                            List<OrderCommodityRelationDTO> orderCommodityRelationList = orderCommodityRelationService.selectList(wrapper);
                            if (CustomizeUtil.listIsNotNull(orderCommodityRelationList)) {
                                for (OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationList) {
                                    OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderCommodityRelationDTO.getOrderId());
                                    if (orderStatusDTO.getOrderState() == 6 || orderStatusDTO.getOrderState() == 7) {
                                        purchaseFeeMoneyScalePrice = purchaseFeeMoneyScalePrice;
                                    } else {
                                        result.setCode(CodeEnum.SHOP_COMMODITY_ORDER_ERROR.getCode());
                                        result.setMsg(CodeEnum.SHOP_COMMODITY_ORDER_ERROR.getMsg());//返回该商品已存在未完成订单
                                        return result;
                                    }
                                }
                            } else {
                                purchaseFeeMoneyScalePrice = purchaseFeeMoneyScalePrice;
                            }
                        }
                    }
                    orderCommodityDetailVO.setPurchaseFeeMoneyScalePrice(purchaseFeeMoneyScalePrice);//询盘砍价服务费
                    purchaseFeeMoneyScalePriceTotal = purchaseFeeMoneyScalePriceTotal.add(purchaseFeeMoneyScalePrice);
                    orderCommodityDetailVO.setPlatBargainStatus(dto.getPlatBargainStatus());
                    orderCommodityDetailVO.setStockDays(dto.getStockDays());//商品备货时间，由后台查询得到
                    orderCommodityDetailVO.setOrganiserUserName(purchaseInfoDTO.getOrganiserUserName());//主办人

                    if (null == orderInfoVO.getOrderCommodityDetailVOList()) {//没有则创建
                        orderInfoVO.setOrderCommodityDetailVOList(new ArrayList<>());
                    }
                    orderInfoVO.getOrderCommodityDetailVOList().add(orderCommodityDetailVO);//添加进订单信息中
                    purchaseOrderType = 1;

                }else {
                    CommodityInfoDTO commodityInfoDTO = commodityInfoService.selectById(orderCommodityBO.getCommodityId());
                    log.info("商品备货时间stockdays:" + commodityInfoDTO.getStockDays() + "----------------------------------------------");
                    if (commodityInfoDTO.getIsPublish() == 0) {
                        return new Result<>(CodeEnum.SHOP_CART_COMMODITY_NOT_PUBLIC);
                    }
                    OrderCommodityDetailVO orderCommodityDetailVO = new OrderCommodityDetailVO();
                    BeanUtils.copyProperties(orderCommodityBO, orderCommodityDetailVO);
                    //判断商品区域
                    boolean shopArea = shopArea(orderCommodityDetailVO.getAvailableArea(), orderInfoVO.getAreaId());
                    OrderCommodityAttrBO orderCommodityAttrBO = new OrderCommodityAttrBO();
                    orderCommodityAttrBO.setBuyersId(buyerId);
                    orderCommodityAttrBO.setCommodityId(orderCommodityDetailVO.getCommodityId());
                    orderCommodityAttrBO.setAtrrIds(orderCommodityDetailVO.getAttrIds());
                    OrderCommodityVO orderCommodityVO = orderCommodityService.queryGoodsPrice(orderCommodityAttrBO);//查询订单优惠
                    orderCommodityDetailVO.setCategoryId(orderCommodityVO.getCategoryId());
                    orderCommodityDetailVO.setSendDays(orderCommodityVO.getSendDays());
                    orderCommodityDetailVO.setWholesaleNum(orderCommodityVO.getBatchNumber());
                    if (!shopArea) {//不满足
                        result.setCode(CodeEnum.SHOP_CART_AREA_ERROR.getCode());
                        result.setMsg(orderCommodityVO.getGoodsName() + CodeEnum.SHOP_CART_AREA_ERROR.getMsg());
                        return result;
                    }
                    //判断商品库存
                    Integer number = orderCommodityService.queryGoodsInventoryNumber(orderCommodityDetailVO.getCommodityId(), orderCommodityDetailVO.getAttrIds());
                    if (number < Integer.parseInt(orderCommodityDetailVO.getCommodityNum())) {//库存不足
                        result.setCode(CodeEnum.SHOP_CART_INVENTORY_ERROR.getCode());
                        result.setMsg(orderCommodityVO.getGoodsName() + CodeEnum.SHOP_CART_INVENTORY_ERROR.getMsg());
                        return result;
                    }

                    BigDecimal commodityDis = discountsPrice(orderCommodityVO,
                            orderCommodityDetailVO.getDiscountsType() + "",
                            orderCommodityDetailVO.getCommodityNum());//此商品的优惠价格计算

                    BigDecimal price = orderCommodityVO.getPrice();//商品单价
                    orderCommodityDetailVO.setSingleCommodityPrice(price);//设置商品单价

                    BigDecimal singleCommodityActualMoney = price.subtract(commodityDis);//单商品实付价格
                    orderCommodityDetailVO.setSingleCommodityRealTotal(singleCommodityActualMoney);//添加单商品实付价格

                    BigDecimal num = new BigDecimal(orderCommodityDetailVO.getCommodityNum());//商品数量
                    shopCommodityNum += num.intValue();//店铺下商品数量
                    orderCommodityDetailVO.setCommodityNum(num.toString());//添加此商品数量

                    BigDecimal totalPrice = price.multiply(num);//商品总价
                    shopTotalMoney = shopTotalMoney.add(totalPrice);//添加进店铺商品总价
                    orderCommodityDetailVO.setCommodityTotal(totalPrice);//添加此商品总价 小计

                    BigDecimal disTotalPrice = commodityDis.multiply(num);//优惠商品总价
                    shopDiscountMoney = shopDiscountMoney.add(disTotalPrice);//店铺优惠总价
                    orderCommodityDetailVO.setCommodityDiscountTotal(disTotalPrice);//添加此商品优惠总价

                    BigDecimal shopTotalPrice = totalPrice.subtract(disTotalPrice);//总价减去优惠总价 实付
                    shopActualMoney = shopActualMoney.add(shopTotalPrice);//店铺应付总价
                    orderCommodityDetailVO.setCommodityRealTotal(shopTotalPrice);//添加此商品总应付价格 实付

//                BigDecimal dividend = new BigDecimal(orderCommodityVO.getDividend());//分润比例
                    BigDecimal dividend = orderCommodityVO.getDividend();//分润比例
//                BigDecimal dividendAllPrice = totalPrice.multiply(dividend).setScale(2, BigDecimal.ROUND_HALF_UP);//分润总价格
                    BigDecimal dividendAllPrice = shopTotalPrice.multiply(dividend).setScale(2, BigDecimal.ROUND_UP);//分润总价格
                    BigDecimal singleDividendAllPrice = singleCommodityActualMoney.multiply(dividend).setScale(2, BigDecimal.ROUND_UP);//单商品分润价格
                    orderCommodityDetailVO.setSingleCommissionMoney(singleDividendAllPrice);//设置单商品分润价格
                    orderCommodityDetailVO.setCommissionMoney(dividendAllPrice);//设置分润总价格
                    commissionMoney = commissionMoney.add(dividendAllPrice);//店铺分润总价

                    orderCommodityDetailVO.setCommissionRate(dividend);//分润比例
                    orderCommodityDetailVO.setTaxRate(orderCommodityVO.getTaxRate());//税率
                    orderCommodityDetailVO.setUnitName(orderCommodityVO.getUnitName());//单位
                    orderCommodityDetailVO.setBrandName(orderCommodityVO.getBrandName());//品牌
                    orderCommodityDetailVO.setAttrName(orderCommodityVO.getAttrName());//规格型号名字
                    orderCommodityDetailVO.setCommodityName(orderCommodityVO.getGoodsName());//商品名称
                    orderCommodityDetailVO.setFirstBalance(orderCommodityVO.getFirstBalance());//首期比例
                    orderCommodityDetailVO.setTailBalance(orderCommodityVO.getTailBalance());//末期比例
                    orderCommodityDetailVO.setWarrantyMonth(orderCommodityVO.getWarrantyMonth());//质保期
                    orderCommodityDetailVO.setWholesalePrice(orderCommodityVO.getWholesalePrice());//批发价

                    orderCommodityDetailVO.setStockDays(commodityInfoDTO.getStockDays());//商品备货时间，由后台查询得到

                    if (null == orderInfoVO.getOrderCommodityDetailVOList()) {//没有则创建
                        orderInfoVO.setOrderCommodityDetailVOList(new ArrayList<>());
                    }
                    orderInfoVO.getOrderCommodityDetailVOList().add(orderCommodityDetailVO);//添加进订单信息中
                    // 处理订单类型
                    CommodityInfoDTO goodsInfo = commodityInfoService.selectById(orderCommodityBO.getCommodityId());
                    Integer isInquiry = goodsInfo.getIsInquiry();
                    if (isInquiry.equals(1)) {
                        type = 1;
                    }
                }
            }
            orderInfoVO.setPurchaseFeeMoneyScalePrice(purchaseFeeMoneyScalePriceTotal);//询盘商品合计服务费
            orderInfoVO.setTotalNum(shopCommodityNum);//数量
            orderInfoVO.setTotalMoney(shopTotalMoney);//小计
            orderInfoVO.setDiscountMoney(shopDiscountMoney);//优惠总价
            orderInfoVO.setActualMoney(shopActualMoney.add(freightMoney));//实付
            orderInfoVO.setFreightMoney(freightMoney);//运费
            orderInfoVO.setCommissionMoney(commissionMoney);//分润
            orderInfoVO.setLastCommissionMoney(commissionMoney);//实际佣金
            // 订单类型
            orderInfoVO.setType(type);
            // 询盘商品类型
            orderInfoVO.setPurchaseOrderType(purchaseOrderType);
            if (null != sysUserDTO) {
                orderInfoVO.setOperatorId(sysUserDTO.getId());
                orderInfoVO.setOperatorName(sysUserDTO.getName());
            }
            orderInfoVOList.add(orderInfoVO);
        }
        List<Long> orderIdList = new ArrayList<>();
//        try {
        log.error("----------2--------------");
        for (OrderInfoVO orderInfoVO : orderInfoVOList) {
            //保存订单
            Long orderId = addOrder(orderDataBO.getNote(), orderInfoVO, orderDataBO.getInvoiceHeadId(), orderDataBO.getOrderInvoiceBO());
            orderIdList.add(orderId);
        }
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error(e.getMessage());
//            throw new RuntimeException(e.getMessage());
//        }
        return new Result<>(orderIdList);
    }


    /**
     * 提交订单
     *
     * @param orderDataBO
     * @return
     */
    public Result<List<Long>> createOrder_bak(OrderDataBO orderDataBO, String sessionId) {
        Long buyerId = orderDataBO.getBuyerShopId();
        //判断是否有电子签章
        ShopQiyuesuoAuthStateInfoBO byQiyuesuoState = shopQiyuesuoInfoService.getByQiyuesuoState(buyerId);
        if (!byQiyuesuoState.isAuthState()) {
            return new Result<>(CodeEnum.CONTACT_SEAL_ERROR);
        }
        //判断是否开户
        ShopInfoDTO shopInfoDTO = shopInfoService.selectById(orderDataBO.getBuyerShopId());
        if (shopInfoDTO.getCiccStatus() == 0) {
            return new Result<>(CodeEnum.FAIL_200003);
        }
        //判断买家基本资质是否过期
        boolean isExpire = shopQualificationService.getIsExpire(orderDataBO.getBuyerShopId());
        if (isExpire) {
            return new Result<>(CodeEnum.FAIL_SHOP_BASIC_CERTIFICATION_EXPIRE_3011);
        }
        HeadParamsBO headParamsBO = CommonParameter.getHeadParamsBO();
        SysUserDTO sysUserDTO = null;
        if (StrUtils.isNotEmpty(sessionId)) {
            sysUserDTO = (SysUserDTO) redisUtil.getSession(sessionId, headParamsBO.getSource() + "");//获取操作人
        }

        //判断重复下单 暂时不要
        Result<List<Long>> result = new Result<>();
        List<OrderInfoVO> orderInfoVOList = new ArrayList<>();
        for (OrderShopInfoBO orderShopInfoBO : orderDataBO.getOrderShopInfoBOList()) {
            Long shopId = orderShopInfoBO.getShopId();
            boolean b = shopInfoService.checkShopIsClose(shopId);
            if (!b) {
                return new Result<>(CodeEnum.SHOP_FREEZE);
            }
            ShopInfoDTO sellShopInfoDTO = shopInfoService.selectById(shopId);
            log.info("卖家店铺信息:{}", sellShopInfoDTO);
            OrderInfoVO orderInfoVO = new OrderInfoVO();
            BeanUtils.copyProperties(orderDataBO, orderInfoVO);
            orderInfoVO.setSellPayType(sellShopInfoDTO.getShopPayType());
            orderInfoVO.setBuyShopId(orderDataBO.getBuyerShopId());//买家店铺id
            orderInfoVO.setSellShopId(shopId);//卖家店铺id
//            orderInfoVO.setType(orderDataBO.getType());//支付方式
            orderInfoVO.setPayType(orderDataBO.getPayType());//订单类型
            orderInfoVO.setPlaceOrderType(orderDataBO.getPlaceOrderType());//下订单类型
            //TODO 订单类型:0普通,1询价
            int type = 0;
            int shopCommodityNum = 0;//店铺下商品总数量
            BigDecimal shopTotalMoney = new BigDecimal("0");//店铺下总价
            BigDecimal shopDiscountMoney = new BigDecimal("0");//店铺下店铺优惠
            BigDecimal shopActualMoney = new BigDecimal("0");//店铺下应付总额
            BigDecimal freightMoney = new BigDecimal("0");//运费
            BigDecimal commissionMoney = new BigDecimal("0");//佣金比例
            for (OrderCommodityBO orderCommodityBO : orderShopInfoBO.getOrderCommodityBOList()) {//店铺下商品
                CommodityInfoDTO commodityInfoDTO = commodityInfoService.selectById(orderCommodityBO.getCommodityId());
                log.info("商品备货时间stockdays:"+commodityInfoDTO.getStockDays()+"----------------------------------------------");
                if (commodityInfoDTO.getIsPublish() == 0) {
                    return new Result<>(CodeEnum.SHOP_CART_COMMODITY_NOT_PUBLIC);
                }
                OrderCommodityDetailVO orderCommodityDetailVO = new OrderCommodityDetailVO();
                BeanUtils.copyProperties(orderCommodityBO, orderCommodityDetailVO);
                //判断商品区域
                boolean shopArea = shopArea(orderCommodityDetailVO.getAvailableArea(), orderInfoVO.getAreaId());
                OrderCommodityAttrBO orderCommodityAttrBO = new OrderCommodityAttrBO();
                orderCommodityAttrBO.setBuyersId(buyerId);
                orderCommodityAttrBO.setCommodityId(orderCommodityDetailVO.getCommodityId());
                orderCommodityAttrBO.setAtrrIds(orderCommodityDetailVO.getAttrIds());
                OrderCommodityVO orderCommodityVO = orderCommodityService.queryGoodsPrice(orderCommodityAttrBO);//查询订单优惠
                orderCommodityDetailVO.setCategoryId(orderCommodityVO.getCategoryId());
                orderCommodityDetailVO.setSendDays(orderCommodityVO.getSendDays());
                orderCommodityDetailVO.setWholesaleNum(orderCommodityVO.getBatchNumber());
                if (!shopArea) {//不满足
                    result.setCode(CodeEnum.SHOP_CART_AREA_ERROR.getCode());
                    result.setMsg(orderCommodityVO.getGoodsName() + CodeEnum.SHOP_CART_AREA_ERROR.getMsg());
                    return result;
                }
                //判断商品库存
                Integer number = orderCommodityService.queryGoodsInventoryNumber(orderCommodityDetailVO.getCommodityId(), orderCommodityDetailVO.getAttrIds());
                if (number < Integer.parseInt(orderCommodityDetailVO.getCommodityNum())) {//库存不足
                    result.setCode(CodeEnum.SHOP_CART_INVENTORY_ERROR.getCode());
                    result.setMsg(orderCommodityVO.getGoodsName() + CodeEnum.SHOP_CART_INVENTORY_ERROR.getMsg());
                    return result;
                }

                BigDecimal commodityDis = discountsPrice(orderCommodityVO,
                        orderCommodityDetailVO.getDiscountsType() + "",
                        orderCommodityDetailVO.getCommodityNum());//此商品的优惠价格计算

                BigDecimal price = orderCommodityVO.getPrice();//商品单价
                orderCommodityDetailVO.setSingleCommodityPrice(price);//设置商品单价

                BigDecimal singleCommodityActualMoney = price.subtract(commodityDis);//单商品实付价格
                orderCommodityDetailVO.setSingleCommodityRealTotal(singleCommodityActualMoney);//添加单商品实付价格

                BigDecimal num = new BigDecimal(orderCommodityDetailVO.getCommodityNum());//商品数量
                shopCommodityNum += num.intValue();//店铺下商品数量
                orderCommodityDetailVO.setCommodityNum(num.toString());//添加此商品数量

                BigDecimal totalPrice = price.multiply(num);//商品总价
                shopTotalMoney = shopTotalMoney.add(totalPrice);//添加进店铺商品总价
                orderCommodityDetailVO.setCommodityTotal(totalPrice);//添加此商品总价 小计

                BigDecimal disTotalPrice = commodityDis.multiply(num);//优惠商品总价
                shopDiscountMoney = shopDiscountMoney.add(disTotalPrice);//店铺优惠总价
                orderCommodityDetailVO.setCommodityDiscountTotal(disTotalPrice);//添加此商品优惠总价

                BigDecimal shopTotalPrice = totalPrice.subtract(disTotalPrice);//总价减去优惠总价 实付
                shopActualMoney = shopActualMoney.add(shopTotalPrice);//店铺应付总价
                orderCommodityDetailVO.setCommodityRealTotal(shopTotalPrice);//添加此商品总应付价格 实付

//                BigDecimal dividend = new BigDecimal(orderCommodityVO.getDividend());//分润比例
                BigDecimal dividend = orderCommodityVO.getDividend();//分润比例
//                BigDecimal dividendAllPrice = totalPrice.multiply(dividend).setScale(2, BigDecimal.ROUND_HALF_UP);//分润总价格
                BigDecimal dividendAllPrice = shopTotalPrice.multiply(dividend).setScale(2, BigDecimal.ROUND_UP);//分润总价格
                BigDecimal singleDividendAllPrice = singleCommodityActualMoney.multiply(dividend).setScale(2, BigDecimal.ROUND_UP);//单商品分润价格
                orderCommodityDetailVO.setSingleCommissionMoney(singleDividendAllPrice);//设置单商品分润价格
                orderCommodityDetailVO.setCommissionMoney(dividendAllPrice);//设置分润总价格
                commissionMoney = commissionMoney.add(dividendAllPrice);//店铺分润总价

                orderCommodityDetailVO.setCommissionRate(dividend);//分润比例
                orderCommodityDetailVO.setTaxRate(orderCommodityVO.getTaxRate());//税率
                orderCommodityDetailVO.setUnitName(orderCommodityVO.getUnitName());//单位
                orderCommodityDetailVO.setBrandName(orderCommodityVO.getBrandName());//品牌
                orderCommodityDetailVO.setAttrName(orderCommodityVO.getAttrName());//规格型号名字
                orderCommodityDetailVO.setCommodityName(orderCommodityVO.getGoodsName());//商品名称
                orderCommodityDetailVO.setFirstBalance(orderCommodityVO.getFirstBalance());//首期比例
                orderCommodityDetailVO.setTailBalance(orderCommodityVO.getTailBalance());//末期比例
                orderCommodityDetailVO.setWarrantyMonth(orderCommodityVO.getWarrantyMonth());//质保期
                orderCommodityDetailVO.setWholesalePrice(orderCommodityVO.getWholesalePrice());//批发价

                orderCommodityDetailVO.setStockDays(commodityInfoDTO.getStockDays());//商品备货时间，由后台查询得到

                if (null == orderInfoVO.getOrderCommodityDetailVOList()) {//没有则创建
                    orderInfoVO.setOrderCommodityDetailVOList(new ArrayList<>());
                }
                orderInfoVO.getOrderCommodityDetailVOList().add(orderCommodityDetailVO);//添加进订单信息中
                // 处理订单类型
                CommodityInfoDTO goodsInfo = commodityInfoService.selectById(orderCommodityBO.getCommodityId());
                Integer isInquiry = goodsInfo.getIsInquiry();
                if (isInquiry.equals(1)) {
                    type = 1;
                }
            }
            orderInfoVO.setTotalNum(shopCommodityNum);//数量
            orderInfoVO.setTotalMoney(shopTotalMoney);//小计
            orderInfoVO.setDiscountMoney(shopDiscountMoney);//优惠总价
            orderInfoVO.setActualMoney(shopActualMoney.add(freightMoney));//实付
            orderInfoVO.setFreightMoney(freightMoney);//运费
            orderInfoVO.setCommissionMoney(commissionMoney);//分润
            // 订单类型
            orderInfoVO.setType(type);
            if (null != sysUserDTO) {
                orderInfoVO.setOperatorId(sysUserDTO.getId());
                orderInfoVO.setOperatorName(sysUserDTO.getName());
            }
            orderInfoVOList.add(orderInfoVO);
        }
        List<Long> orderIdList = new ArrayList<>();
        try {
            for (OrderInfoVO orderInfoVO : orderInfoVOList) {
                //保存订单
                Long orderId = addOrder(orderDataBO.getNote(), orderInfoVO, orderDataBO.getInvoiceHeadId(), orderDataBO.getOrderInvoiceBO());
                orderIdList.add(orderId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return new Result<>(orderIdList);
    }


    /**
     * 确定订单接口
     *
     * @param orderIds
     * @return
     */
    @Transactional
    @Override
    public List<OrderContractVO> sureOrder(String orderIds, Long signShopId, int type, List<byte[]> bytes) {
        List<String> orderIdList = Arrays.asList(orderIds.split(","));
        List<OrderContractVO> orderContractVOList = new ArrayList<>();
        for (int i = 0; i < orderIdList.size(); i++) {
            OrderContractVO orderContractVO = sureOrder(Long.parseLong(orderIdList.get(i)), signShopId, type, bytes.get(i), orderIds, "");
            orderContractVOList.add(orderContractVO);
        }
        return orderContractVOList;
    }

    /**
     * 获取带确认页面订单信息
     *
     * @param ids
     * @return
     */
    @Override
    public List<OrderInfoVO> getOrderInfoByOrderId(String ids) {
        List<OrderInfoVO> orderInfoVOList = new ArrayList<>();
        String[] idList = ids.split(",");
        for (String id : idList) {
            OrderInfoVO orderInfoVO = getOrderInfoById(id);
            if (null == orderInfoVO) {
                continue;
            }
            orderInfoVOList.add(orderInfoVO);
        }
        return orderInfoVOList;
    }


    @Override
    public OrderDetailsVO getOrderDetailsById(Long id) {
        OrderDetailsVO details = null;
        OrderInfoDTO orderInfoDTO = baseMapper.selectById(id);
        if(null != orderInfoDTO.getPurchaseOrderType() && orderInfoDTO.getPurchaseOrderType() == BargainStateEnum.PURCHASE_ORDER_TYPE.getCode()){
            details = baseMapper.getPurchaseOrderDetailsById(id);
        }else {
            details = baseMapper.getOrderDetailsById(id);
        }

        if (details == null) {
            return null;
        }


        //查询卖家是否设置支付类型
        Wrapper<OrderPaymentTypeDTO> paymentWrapper = new EntityWrapper<>();
        paymentWrapper.eq("order_id", id);
        List<OrderPaymentTypeDTO> orderPaymentTypeDTOList  = orderPaymentTypeService.selectList(paymentWrapper);
        List<OrderPaymentScaleVO>  orderPaymentScaleVOList = new ArrayList<>();
        List<OrderPaymentTypeVO> orderPaymentTypeVOList = new ArrayList<>();
        if(CustomizeUtil.listIsNotNull(orderPaymentTypeDTOList)){
            for(OrderPaymentTypeDTO orderPaymentTypeDTO : orderPaymentTypeDTOList){
                OrderPaymentTypeVO  orderPaymentTypeVO = new OrderPaymentTypeVO();
                BeanUtils.copyProperties(orderPaymentTypeDTO,orderPaymentTypeVO);
                if(orderPaymentTypeVO.getPaymentType() == OrderConstant.ORDER_PAYMENT_TYPE_CREDIT){//如果卖家设置了赊销，则获取赊销规则
                    //查询卖家设置的赊销规则
                    Wrapper<OrderPaymentScaleDTO> paymentScaleWrapper = new EntityWrapper<>();
                    paymentScaleWrapper.eq("order_id", id);
                    paymentScaleWrapper.eq("payment_id",orderPaymentTypeVO.getId());
                    List<OrderPaymentScaleDTO> orderPaymentScaleDTOList = orderPaymentScaleService.selectList(paymentScaleWrapper);
                    if(CustomizeUtil.listIsNotNull(orderPaymentScaleDTOList)){
                        //list转换
                        for(OrderPaymentScaleDTO orderPaymentScaleDTO : orderPaymentScaleDTOList){
                            OrderPaymentScaleVO orderPaymentScaleVO = new OrderPaymentScaleVO();
                            BeanUtils.copyProperties(orderPaymentScaleDTO,orderPaymentScaleVO);
                            orderPaymentScaleVOList.add(orderPaymentScaleVO);
                        }
                    }
                    orderPaymentTypeVO.setOrderPaymentScaleVOList(orderPaymentScaleVOList);
                }
                orderPaymentTypeVOList.add(orderPaymentTypeVO);
            }
            details.setPaymentTypeVOList(orderPaymentTypeVOList);
        }

        if (CustomizeUtil.listIsNotNull(details.getOrderItem())) {
            for (OrderInfoGoodsVO orderGoods : details.getOrderItem()) {
                String logUrl = orderGoods.getLogUrl();
                if(StringUtils.isEmpty(logUrl)){
                    orderGoods.setLogUrl(orderGoods.getPurchaseCommodityUrl());
                }
                // 商品id
                Long goodsId = orderGoods.getCommodityId();
                // 订单商品id
                Long orderGoodsId = orderGoods.getId();
                // 处理商品链接
                String goodsUrl = GOODS_URL + goodsId + "&type=0";
                orderGoods.setGoodsUrl(goodsUrl);
                // 获取订单商品售后表id
                Wrapper<OrderReturnCommodityDTO> wrapper = new EntityWrapper<>();
                wrapper.eq("order_commodity_id", orderGoodsId);
                OrderReturnCommodityDTO selectOne = orderReturnCommodityService.selectOne(wrapper);
                if (selectOne != null) {
                    orderGoods.setOrderReturnCommodityId(selectOne.getId());
                    orderGoods.setAfterSalesState(selectOne.getAfterSalesState());
                }
            }
        }
        //TODO 获取订单头部信息
        OrderDetailsHeaderVO headerVO = baseMapper.queryOrderDetailsHeaders(details.getId());
        if (headerVO != null) {
            details.setHeaders(headerVO);
        }


        // 获取订单发票信息
        Wrapper<OrderInvoiceDTO> invoiceDTOWrapper = new EntityWrapper<>();
        invoiceDTOWrapper.eq("order_id", id);
        OrderInvoiceDTO orderInvoiceDTO = orderInvoiceService.selectOne(invoiceDTOWrapper);
        if (orderInvoiceDTO != null) {
            OrderInvoiceDetailsVO vo = orderInvoiceService.queryById(orderInvoiceDTO.getId());
            details.setOrderInvoiceInformation(vo);
        }

        //获取发货信息
        List<OrderShipDTO> orderShip = orderShipService.getListByOrderId(id);
        details.setShipList(orderShip);

        //查看是否是有票据支付
        Wrapper  wrapper = new EntityWrapper();
        wrapper.eq("order_id", id);
//        wrapper.eq("pay_state", 1);
//        wrapper.eq("pay_type", 2);
//        OrderPayRelationDTO relationDTO = orderPayRelationService.selectOne(wrapper);
//        if(relationDTO != null){
//            details.setBillPayStatus(1);
//            details.setBillName(relationDTO.getBillName());
//            details.setBillUrl(relationDTO.getBillUrl());
//        }
        int billPayStatus = 0;//票据支付状态:0未支付、1支付中
        List<OrderPayRelationDTO> relationDTOList = orderPayRelationService.selectList(wrapper);
        if(relationDTOList != null && relationDTOList.size() > 0){
            for(OrderPayRelationDTO dto : relationDTOList){
                if(dto.getPayType() != null && dto.getPayType() == 2 && dto.getPayState() == 1){
                    billPayStatus = 1;
                    details.setBillName(dto.getBillName());
                    details.setBillUrl(dto.getBillUrl());
                    break;
                }
            }
        }
        details.setBillPayStatus(billPayStatus);
        details.setRelationDTOList(relationDTOList);

        details.setRefundPayMoney(this.baseMapper.getRefundPayMoney(id));//退款支付金额金额
        //维权
        EntityWrapper<OrderRightsProtectionDTO> orderRightsProtectionDTOEntityWrapper = new EntityWrapper<>();
        orderRightsProtectionDTOEntityWrapper.eq("order_id",id);
        List<OrderRightsProtectionDTO> orderRightsProtectionDTOS = orderRightsProtectionService.selectList(orderRightsProtectionDTOEntityWrapper);
        details.setOrderRightsProtectionDTOList(orderRightsProtectionDTOS);
        return details;
    }



    /**
     * 获取待确认订单信息
     *
     * @param id 订单id
     * @return
     */
    private OrderInfoVO getOrderInfoById(String id) {
        OrderInfoDTO orderInfoDTO = baseMapper.selectById(id);
        if (null == orderInfoDTO) {
            return null;
        }
        //查询是否改价
        OrderCommodityRelationDTO orderCommodityRelationDTO = orderCommodityRelationService.getByOrderId(Long.parseLong(id)).get(0);
        OrderInfoVO orderInfoVO = new OrderInfoVO();
        List<OrderCommodityDetailVO> orderCommodityDetailVOList = new ArrayList<>();
        BeanUtils.copyProperties(orderInfoDTO, orderInfoVO);
        if (orderInfoDTO.getType() == 1) {//询价
            orderInfoVO.setIsChangePrice(orderCommodityRelationDTO.getIsChangePrice());
        }
        List<OrderCommodityRelationDTO> orderCommodityDTOs = orderCommodityRelationService.getByOrderId(Long.parseLong(id));
        for (OrderCommodityRelationDTO orderCommodityDTO : orderCommodityDTOs) {
            OrderCommodityDetailVO orderCommodityDetailVO = new OrderCommodityDetailVO();
            BeanUtils.copyProperties(orderCommodityDTO, orderCommodityDetailVO);
            orderCommodityDetailVO.setNewSingleCommodityPrice(orderCommodityDTO.getSingleActualMoney());
            orderCommodityDetailVO.setSingleCommodityPrice(orderCommodityDTO.getPrice());
            orderCommodityDetailVO.setCommodityNum(orderCommodityDTO.getNum().toString());
            orderCommodityDetailVO.setCommissionMoney(orderCommodityDTO.getMoeny());
            orderCommodityDetailVO.setCommodityDiscountTotal(orderCommodityDTO.getDiscountMoney());
            orderCommodityDetailVO.setCommodityRealTotal(orderCommodityDTO.getActualMoney());
            orderCommodityDetailVO.setDiscountsType(orderCommodityDTO.getDiscountType());
            orderCommodityDetailVO.setTaxRate(orderCommodityDTO.getTaxRate());
            orderCommodityDetailVO.setUnitName(orderCommodityDTO.getUnitName());
            orderCommodityDetailVO.setBrandName(orderCommodityDTO.getBrandName());
            orderCommodityDetailVO.setAttrName(orderCommodityDTO.getAttrName());
            orderCommodityDetailVO.setCommodityName(orderCommodityDTO.getCommodityName());
            orderCommodityDetailVO.setCommodityTotal(orderCommodityDTO.getMoeny());
            orderCommodityDetailVO.setIsChangePrice(orderCommodityDTO.getIsChangePrice());
            if(orderCommodityDTO.getPurchaseCommodityType() == BargainStateEnum.PURCHASE_COMMODITY_OK.getCode()){
                orderCommodityDetailVO.setWhetherToAskForAQuotation(0);//询盘商品没有询价
            }else{
                // 获取商品类型
                CommodityInfoDTO commodityInfoDTO = commodityInfoService.selectById(orderCommodityDTO.getCommodityId());
                orderCommodityDetailVO.setWhetherToAskForAQuotation(commodityInfoDTO.getIsInquiry());
            }
            orderCommodityDetailVOList.add(orderCommodityDetailVO);
        }
        orderInfoVO.setOrderCommodityDetailVOList(orderCommodityDetailVOList);

        //获取订单支付类型
        Wrapper<OrderPaymentTypeDTO> paymentWrapper = new EntityWrapper<>();
        paymentWrapper.eq("order_id", id);
        List<OrderPaymentTypeDTO> orderPaymentTypeDTOList  = orderPaymentTypeService.selectList(paymentWrapper);
        List<OrderPaymentScaleVO>  orderPaymentScaleVOList = new ArrayList<>();
        List<OrderPaymentTypeVO> orderPaymentTypeVOList = new ArrayList<>();
        if(CustomizeUtil.listIsNotNull(orderPaymentTypeDTOList)){
            for(OrderPaymentTypeDTO orderPaymentTypeDTO : orderPaymentTypeDTOList){
                OrderPaymentTypeVO  orderPaymentTypeVO = new OrderPaymentTypeVO();
                BeanUtils.copyProperties(orderPaymentTypeDTO,orderPaymentTypeVO);
                if(orderPaymentTypeVO.getPaymentType() == OrderConstant.ORDER_PAYMENT_TYPE_CREDIT){//如果卖家设置了赊销，则获取赊销规则
                    //查询卖家设置的赊销规则
                    Wrapper<OrderPaymentScaleDTO> paymentScaleWrapper = new EntityWrapper<>();
                    paymentScaleWrapper.eq("order_id", id);
                    paymentScaleWrapper.eq("payment_id",orderPaymentTypeVO.getId());
                    List<OrderPaymentScaleDTO> orderPaymentScaleDTOList = orderPaymentScaleService.selectList(paymentScaleWrapper);
                    if(CustomizeUtil.listIsNotNull(orderPaymentScaleDTOList)){
                        //list转换
                        for(OrderPaymentScaleDTO orderPaymentScaleDTO : orderPaymentScaleDTOList){
                            OrderPaymentScaleVO orderPaymentScaleVO = new OrderPaymentScaleVO();
                            BeanUtils.copyProperties(orderPaymentScaleDTO,orderPaymentScaleVO);
                            orderPaymentScaleVOList.add(orderPaymentScaleVO);
                        }
                    }
                    orderPaymentTypeVO.setOrderPaymentScaleVOList(orderPaymentScaleVOList);
                }
                orderPaymentTypeVOList.add(orderPaymentTypeVO);
            }
            orderInfoVO.setPaymentTypeVOList(orderPaymentTypeVOList);
        }
        return orderInfoVO;
    }

    /**
     * 单订单确定
     *
     * @param orderId    订单id
     * @param signShopId 签署人店铺id
     * @param type       1单订单 2多订单
     * @return 合同地址
     */
    private OrderContractVO sureOrder(Long orderId, Long signShopId, int type, byte[] bytes, String orderIds, String affix) {
        //修改订单状态 待签合同
        OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderId);
        if (orderStatusDTO.getOrderState() != OrderStateEnum.ORDER_STATE_ENUM_WAIT_SURE.getCode()) {//此订单已经确认过
            return null;
        }
        orderStatusDTO.setOrderState(OrderStateEnum.ORDER_STATE_ENUM_WAIT_CONTACT.getCode());
        orderStatusService.updateById(orderStatusDTO);
        // 添加订单确认时间
        OrderTimeRecordSaveBO timeRecordSaveBO = new OrderTimeRecordSaveBO();
        timeRecordSaveBO.setOrderId(orderId);
        timeRecordSaveBO.setOrderState(1);
        orderTimeRecordService.add(timeRecordSaveBO);
        OrderInfoDTO orderInfoDTO = baseMapper.selectById(orderId);

        Long one = System.currentTimeMillis();
        //卖家发送短信
        try {
            sendMessage(Arrays.asList(orderInfoDTO.getSellShopId()));
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("发送短信失败");
            e.printStackTrace();
        }
        Long two = System.currentTimeMillis();
        log.info("---卖家发送短信消耗时间："+(two-one));
        //发送站内信
        try {
            sendWebMessageInChangeOrderStatus(orderInfoDTO.getSellShopId(), 2, orderId);
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("发送站内信失败");
            e.printStackTrace();
        }
        Long three = System.currentTimeMillis();
        log.info("---发送站内信消耗时间："+(three-two));

        //发起合同并返回签署合同地址
        String contactId = shopQiyuesuoInfoService.promoteContract(orderInfoDTO.getBuyShopId(), orderInfoDTO.getSellShopId(), orderId, null, bytes, affix);
        log.info("发起合同后的合同id:{}", contactId);
        String signaturePage = orderContractRelationService.getSignaturePage(orderId, signShopId, type, orderIds, Long.parseLong(contactId));
        log.info("发起合同后的合同签属地址:{}", signaturePage);

        Long four = System.currentTimeMillis();
        log.info("---发起合同消耗时间："+(four-three));
        //添加合同订单表
        OrderContractRelationSaveBO orderContractRelationSaveBO = new OrderContractRelationSaveBO();
        orderContractRelationSaveBO.setOrderId(orderId);
        orderContractRelationSaveBO.setContractId(contactId);
        orderContractRelationSaveBO.setFileUrl(signaturePage);
        ContractTempletDTO contractTempletDTO = contractTempletService.getDefaultContract();
        orderContractRelationSaveBO.setTempletName(contractTempletDTO.getContractName());
        orderContractRelationSaveBO.setTempletId(contractTempletDTO.getTemplateId());
        Long orderContractId = orderContractRelationService.addAndReturnId(orderContractRelationSaveBO);//添加进订单合同关系表

        //更新订单合同参数表
        OrderContractParamRelationDTO orderContractParamRelationDTO = orderContractParamRelationService.getByOrderId(orderId);
        orderContractParamRelationDTO.setOrderContractId(orderContractId);
        orderContractParamRelationService.updateById(orderContractParamRelationDTO);

        OrderContractVO orderContractVO = new OrderContractVO();
        orderContractVO.setOrderId(orderId);
        orderContractVO.setOrderNo(orderInfoDTO.getOrderNo());
        orderContractVO.setContactName(contractTempletDTO.getContractName());
        orderContractVO.setOrderMoney(orderInfoDTO.getActualMoney());
        orderContractVO.setContactUrl(signaturePage);
        orderContractVO.setSignPlayerType(1);
        orderContractVO.setContractState(orderStatusDTO.getContactState());
        orderContractVO.setContactId(contactId);
        Long five = System.currentTimeMillis();
        log.info("---确定订单消耗时间："+(five-one));
        log.info("sureOrder-------"+orderId);

        //赊销支付类型重新生成订单支付关系
        reAddOrderPayRelation(orderId);
        return orderContractVO;
    }

    private void reAddOrderPayRelation(Long orderId){
        //获取订单支付类型（如果是赊销类型，需要重新生成订单支付关系）
        Wrapper<OrderPaymentTypeDTO> paymentWrapper = new EntityWrapper<>();
        paymentWrapper.eq("order_id", orderId);
        List<OrderPaymentTypeDTO> orderPaymentTypeDTOList  = orderPaymentTypeService.selectList(paymentWrapper);
        List<OrderPaymentScaleVO>  orderPaymentScaleVOList = new ArrayList<>();
        List<OrderPaymentTypeVO> orderPaymentTypeVOList = new ArrayList<>();
        if(CustomizeUtil.listIsNotNull(orderPaymentTypeDTOList)){
            for(OrderPaymentTypeDTO orderPaymentTypeDTO : orderPaymentTypeDTOList){
                OrderPaymentTypeVO  orderPaymentTypeVO = new OrderPaymentTypeVO();
                BeanUtils.copyProperties(orderPaymentTypeDTO,orderPaymentTypeVO);
                if(orderPaymentTypeVO.getType() == 1 && orderPaymentTypeVO.getPaymentType() == OrderConstant.ORDER_PAYMENT_TYPE_CREDIT){//如果卖家设置了赊销，且买家确认了赊销，则获取赊销规则
                    //查询卖家设置的赊销规则
                    Wrapper<OrderPaymentScaleDTO> paymentScaleWrapper = new EntityWrapper<>();
                    paymentScaleWrapper.eq("order_id", orderId);
                    paymentScaleWrapper.eq("payment_id",orderPaymentTypeVO.getId());
                    List<OrderPaymentScaleDTO> orderPaymentScaleDTOList = orderPaymentScaleService.selectList(paymentScaleWrapper);
                    if(CustomizeUtil.listIsNotNull(orderPaymentScaleDTOList)){
                        //OrderPayRelationDTO orderPayRelationDTO = orderPayRelationService.getByOrderIdAndPeriods(orderId,1);
                        //删除对应的支付关系
                        Wrapper<OrderPayRelationDTO> orderPayRelationDTOWrapper = new EntityWrapper<>();
                        orderPayRelationDTOWrapper.eq("order_id", orderId);
                        OrderPayRelationDTO orderPayRelation = orderPayRelationService.getByOrderIdAndPeriods(orderId,1);

                        orderPayRelationService.delete(orderPayRelationDTOWrapper);
                        for(int i = 0; i<orderPaymentScaleDTOList.size() ; i++){
                            OrderPaymentScaleDTO orderPaymentScaleDTO = orderPaymentScaleDTOList.get(i);
                            Long id = ymlConfig.getPkId();
                            OrderPayRelationDTO orderPayRelationDTO = new OrderPayRelationDTO();
                            orderPayRelationDTO.setOrderId(orderId);
                            orderPayRelationDTO.setId(id);
                            orderPayRelationDTO.setRealPayMoney(orderPaymentScaleDTO.getPaymentAmount());
                            if(i == 0){
                                orderPayRelationDTO.setCommissionMoney(orderPayRelation.getCommissionMoney());
                            }
                            orderPayRelationDTO.setPayState(0);
                            orderPayRelationDTO.setPeriods(orderPaymentScaleDTO.getPeriods());//i期
                            orderPayRelationService.insert(orderPayRelationDTO);
                            orderPaymentScaleDTO.setPayRelationId(id);
                            orderPaymentScaleService.updateById(orderPaymentScaleDTO);
                        }
                    }
                }
            }
        }
    }

    /**
     * 发送短信
     *
     * @param shopIdList 店铺idList
     */
    @Override
    public void sendMessage(List<Long> shopIdList) {
        try {
            log.info("0-------sendMessage---------shopIdList:"+shopIdList);
            List<ShopInfoVO> shopInfoVOS = shopInfoService.getByShopIds(shopIdList);
            SmsInfoSaveBO smsInfoSaveBO = new SmsInfoSaveBO();
            for (ShopInfoVO shopInfoVO : shopInfoVOS) {
                smsInfoSaveBO.setMobile(shopInfoVO.getMobile());
                smsInfoService.saveOrderStatus(smsInfoSaveBO);
            }
        } catch (Exception e) {
            log.error("发送短信错误信息:{}", e.getMessage());
        }
    }

    /**
     * 发送站内信 当订单状态发生改变
     *
     * @param shopId  店铺id
     * @param type    1买家 2卖家
     * @param orderId 订单id
     */
    @Override
    public void sendWebMessageInChangeOrderStatus(Long shopId, int type, Long orderId) {
        try {
            OrderInfoDTO orderInfoDTO = orderInfoMapper.selectById(orderId);
            log.info("0--------sendWebMessageInChangeOrderStatus--------orderId:"+orderInfoDTO.getPurchaseOrderType());
            ResponseDTO responseDTO = new ResponseDTO();
            MessageAnnouncementSaveBO messageAnnouncementSaveBO = new MessageAnnouncementSaveBO();
            messageAnnouncementSaveBO.setJumpType(MessageEnum.ORDER_STATUS_CHANGE.getCode() + "");
            messageAnnouncementSaveBO.setType(MessageEnum.SYS_MESSAGE.getCode());
            messageAnnouncementSaveBO.setTitle("您有一条订单状态改变，请去查看");
            messageAnnouncementSaveBO.setContent("您有一条订单状态改变，请去查看");
            messageAnnouncementSaveBO.setShopId(shopId);
            messageAnnouncementSaveBO.setShopType(type);
            messageAnnouncementSaveBO.setTextType(1);
            messageAnnouncementSaveBO.setKey(orderId + "");

            if(null != orderInfoDTO.getPurchaseOrderType()){
                messageAnnouncementSaveBO.setPurchaseOrderType(orderInfoDTO.getPurchaseOrderType());//询盘订单或普通订单
            }else{
                messageAnnouncementSaveBO.setPurchaseOrderType(0);//普通订单
            }
            responseDTO.setMessageId(shopId + "");
            responseDTO.setData(messageAnnouncementSaveBO);
            log.info("4----------------orderId:"+JSON.toJSONString(responseDTO));
            kafkaProducerService.senMessage(JSON.toJSONString(responseDTO), MessageTopicType.COMMENT_MESSAGE_TOPIC);
        } catch (Exception e) {
            log.error("发送站内信错误信息:{}", e.getMessage());
        }
    }

    /**
     * 发送站内信 签署废弃合同
     *
     * @param orderId 订单id
     */
    public void sendSignAbandonContact(Long orderId) {
        OrderInfoDTO orderInfoDTO = selectById(orderId);
        ResponseDTO responseDTO = new ResponseDTO();
        MessageAnnouncementSaveBO messageAnnouncementSaveBO = new MessageAnnouncementSaveBO();
        messageAnnouncementSaveBO.setJumpType(MessageEnum.ORDER_SING_ABANDON.getCode() + "");
        messageAnnouncementSaveBO.setType(MessageEnum.SYS_MESSAGE.getCode());
        messageAnnouncementSaveBO.setTitle("您有一份废弃合同待签署，请去查看");
        messageAnnouncementSaveBO.setContent("您有一份废弃合同待签署，请去查看");
        messageAnnouncementSaveBO.setShopId(orderInfoDTO.getBuyShopId());
        messageAnnouncementSaveBO.setShopType(MessageEnum.SHOP_TYPE_1.getCode());
        messageAnnouncementSaveBO.setTextType(1);
        messageAnnouncementSaveBO.setKey(orderId + "");
        responseDTO.setMessageId(orderInfoDTO.getBuyShopId() + "");
        responseDTO.setData(messageAnnouncementSaveBO);
        kafkaProducerService.senMessage(JSON.toJSONString(responseDTO), MessageTopicType.COMMENT_MESSAGE_TOPIC);
//
        messageAnnouncementSaveBO.setShopType(MessageEnum.SHOP_TYPE_2.getCode());
        messageAnnouncementSaveBO.setShopId(orderInfoDTO.getSellShopId());
        responseDTO.setMessageId(orderInfoDTO.getSellShopId() + "");
        responseDTO.setData(messageAnnouncementSaveBO);
        kafkaProducerService.senMessage(JSON.toJSONString(responseDTO), MessageTopicType.COMMENT_MESSAGE_TOPIC);

    }

    /**
     * 判断商品区域
     *
     * @param availableArea 可售区域
     * @param areaId        收货地址区域
     * @return
     */
    private boolean shopArea(String availableArea, Long areaId) {
        if ("0".equals(availableArea)) {
            return true;
        }
        if (StrUtils.isEmpty(availableArea)) {
            return false;
        }
        String[] split = availableArea.split(",");
        String[] areaList = split;
        SysAreaDTO areaStair = sysAreaService.getAreaStair(areaId);
        Long areaStairId = areaStair.getId();//区域一级id
        for (String s : areaList) {
            if (s.equals(areaStairId.toString())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 返回商品的优惠价
     *
     * @param orderCommodityVO
     * @param type             0没选择折扣 1批发 2会员
     * @param num              商品数量
     * @return
     */
    private BigDecimal discountsPrice(OrderCommodityVO orderCommodityVO, String type, String num) {
        if ("0".equals(type)) {//没有选择
            return new BigDecimal(0);
        }
        if ("2".equals(type)) {//2会员折扣
            return orderCommodityVO.getPrice().subtract
                    (orderCommodityVO.getMemberDiscount().multiply(orderCommodityVO.getPrice()));
        }
        if(orderCommodityVO.getBatchNumber() != null && orderCommodityVO.getWholesalePrice() != null){
            //批发价
            if (Integer.parseInt(num) < orderCommodityVO.getBatchNumber()) {//不满足批发数量
                return new BigDecimal(0);
            }
            return orderCommodityVO.getPrice().subtract(orderCommodityVO.getWholesalePrice());
        }
        return new BigDecimal(0);
    }

    /**
     * 返回订单id
     * 下订单
     *
     * @param orderInfoVO
     * @return
     */
    private Long addOrder(String orderNote, OrderInfoVO orderInfoVO, Long invoiceHeadId, OrderInvoiceBO orderInvoiceBO) {
        OrderInfoDTO dto = new OrderInfoDTO();
        BeanUtils.copyProperties(orderInfoVO, dto);
        //ShopAddressDTO shopAddressDTO = shopAddressService.selectById(orderInfoVO.getAddressId());
        dto.setUserName(orderInfoVO.getUserName());//收货人
        dto.setUserMobile(orderInfoVO.getUserMobile());//收货人电话
        dto.setUserAddress(orderInfoVO.getUserAddress());//收货人地址
        dto.setOrderNote(orderNote);//订单备注
        dto.setOrderNo(CustomizeUtil.getOrderNo());//订单编号
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        this.insert(dto);//添加订单表
        orderInfoVO.setId(id);
        //添加订单发票信息
        boolean b = false;
        try {
            b = orderInvoiceService.addByOrderInfo(orderInfoVO, invoiceHeadId, orderInvoiceBO);
        } catch (Exception e) {
            log.error("添加发票失败",e);
            throw new RuntimeException("添加发票失败");
        }
        if (!b) {
            throw new RuntimeException("添加发票失败");
        }
        List<String> ids = new ArrayList<>();
        //添加进订单商品表
        try {
            ids = orderCommodityRelationService.addByOrderInfo(orderInfoVO);
        } catch (Exception e) {
            log.error("添加进订单商品失败",e);
            throw new RuntimeException("添加进订单商品失败");
        }
        //添加进支付表中
        boolean b2 = false;
        try {
            b2 = orderPayRelationService.addByOrderInfo(orderInfoVO);
        } catch (Exception e) {
            log.error("支付信息添加失败",e);
            throw new RuntimeException("");
        }
        if (!b2) {
            throw new RuntimeException("支付信息添加失败");
        }

        //订单状态
        boolean b3 = false;
        try {
            b3 = orderStatusService.addByOrderInfo(id, invoiceHeadId);
        } catch (Exception e) {
            log.error("订单状态添加失败",e);
            throw new RuntimeException("订单状态添加失败");
        }
        if (!b3) {
            throw new RuntimeException("订单状态添加失败");
        }
        //订单提交日志
        boolean b4 = false;
        try {
            b4 = orderProcessLogService.addByOrderInfo(id, OrderStateEnum.ORDER_SUBMIT.getCode());
        } catch (Exception e) {
            log.error("订单日志添加失败",e);
            throw new RuntimeException("订单日志添加失败");
        }
        if (!b4) {
            throw new RuntimeException("订单日志添加失败");
        }
        //添加订单合同参数表
        boolean b5 = false;
        try {
            b5 = orderContractParamRelationService.addDefaultContent(orderInfoVO, orderInvoiceBO, ids);
        } catch (Exception e) {
            log.error("订单日志添加失败",e);
            throw new RuntimeException("订单日志添加失败");
        }
        if (!b5) {
            throw new RuntimeException("订单合同参数添加失败");
        }
        //添加进支付类型表
        boolean b6 = false;
        try {
            b6 = orderPaymentTypeService.saveDefaultOrderPaymentType(orderInfoVO);
        } catch (Exception e) {
            log.error("添加进支付类型失败",e);
            throw new RuntimeException("添加进支付类型失败");
        }
        if (!b6) {
            throw new RuntimeException("添加进支付类型失败");
        }

        return id;
    }

    @Override
    public boolean add(OrderInfoSaveBO orderInfoSaveBO) {
        OrderInfoDTO dto = new OrderInfoDTO();
        BeanUtils.copyProperties(orderInfoSaveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }





    @Override
    public BigDecimal getBuyShopConsumption(Long buyShopId, Long sellShopId) {
        Wrapper<OrderInfoDTO> wrapper = new EntityWrapper<>();
        //订单状态 0创建、1买家确定、2买家签合同、3卖家签合同，4待、5待发货、6待收货、7已收货、8已评价、9申请退货、10、买家发货、11卖家收货、12已退款、13取消订单、14删除订单,15订单已完成
        wrapper.eq("sell_shop_id", sellShopId)
                .eq("buy_shop_id", buyShopId);
        List<OrderInfoDTO> orderInfoDTOS = this.selectList(wrapper);
        BigDecimal total = new BigDecimal(0);
        for (OrderInfoDTO dto : orderInfoDTOS) {
            Wrapper<OrderStatusDTO> swrapper = new EntityWrapper<>();
            swrapper.eq("order_id", dto.getId());
            OrderStatusDTO orderStatusDTO = orderStatusService.selectOne(swrapper);
            if (orderStatusDTO != null && orderStatusDTO.getOrderState() == 5) {
                total = total.add(dto.getActualMoney());
            }
        }
        return total;
    }

    @Override
    public String getShopOrderAfterSale(Long shopId) {
        Wrapper<OrderInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("sell_shop_id", shopId);
        int total = this.selectCount(wrapper);
        if (total <= 0) {
            return "0";
        }

        Wrapper<OrderReturnCommodityDTO> returnWrapper = new EntityWrapper<>();
        returnWrapper.eq("seller_shop_id", shopId);
        int returnTotal = orderReturnCommodityService.selectCount(returnWrapper);
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        return df.format((float) returnTotal / total);//售后评分
    }

    /**
     * 修改合同
     *
     * @param orderContractParamRelationDTO
     * @param bytes
     * @return
     */
    @Override
    public Result<String> updateContactByOrderId(OrderContractParamRelationDTO orderContractParamRelationDTO, String param, byte[] bytes) throws IOException {
        Long orderId = orderContractParamRelationDTO.getOrderId();
        OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderId);
        if (!(orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_NO_SIGN.getCode() ||
                orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGNING.getCode())) {//买家已经签订了合同，不能修改
            return new Result<>(CodeEnum.FAIL_UPDATE_CONTACT_310005);
        }
        String contactUrl = orderContractRelationService.updateByOrderId(param, orderId, bytes);
        String remarks = orderContractParamRelationDTO.getRemarks();
        String orderCommodityIds = orderContractParamRelationDTO.getOrderCommodityIds();
        List<String> strings = JSONArray.parseArray(remarks, String.class);
        List<String> orderCommodityIdList = Arrays.asList(orderCommodityIds.split(","));
        for (int i = 0; i < orderCommodityIdList.size(); i++) {//更新订单商品备注
            OrderCommodityRelationDTO orderCommodityRelationDTO = orderCommodityRelationService.selectById(Long.parseLong(orderCommodityIdList.get(i)));
            orderCommodityRelationDTO.setRemark(strings.get(i));
            orderCommodityRelationService.updateById(orderCommodityRelationDTO);
        }
        orderContractParamRelationService.updateById(orderContractParamRelationDTO);//更新订单合同内容
        return new Result<>(contactUrl);
    }

    /**
     * 催促签订合同 买家催促卖家
     *
     * @param orderId
     * @return
     */
    @Override
    public boolean urgeSignContact(Long orderId, Long sellShopId) {
        OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderId);
        orderStatusDTO.setUrgeSign(1);
        orderStatusService.updateById(orderStatusDTO);

        ResponseDTO responseDTO = new ResponseDTO();
        responseDTO.setMessageId(sellShopId + "");
        MessageAnnouncementSaveBO messageAnnouncementSaveBO = new MessageAnnouncementSaveBO();
        messageAnnouncementSaveBO.setType(MessageEnum.SYS_MESSAGE.getCode());
        messageAnnouncementSaveBO.setShopId(sellShopId);
        messageAnnouncementSaveBO.setTitle("催促签订");
        messageAnnouncementSaveBO.setContent("催促签订");
        messageAnnouncementSaveBO.setTextType(1);
        messageAnnouncementSaveBO.setJumpType(MessageEnum.SIGN_CONTACT_MESSAGE.getCode() + "");
        messageAnnouncementSaveBO.setShopType(MessageEnum.SHOP_TYPE_2.getCode());
        messageAnnouncementSaveBO.setKey(orderId + "");
        responseDTO.setData(messageAnnouncementSaveBO);
        kafkaProducerService.senMessage(JSON.toJSONString(responseDTO), MessageTopicType.COMMENT_MESSAGE_TOPIC);
        return true;
    }

    /**
     * 催促发货 买家催促卖家
     *
     * @param orderId
     * @return
     */
    @Override
    public void urgeShipments(Long orderId, Long sellShopId) {
        OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderId);
        orderStatusDTO.setUrgeDeliverGoods(1);
        orderStatusService.updateById(orderStatusDTO);
        ResponseDTO responseDTO = new ResponseDTO();
        responseDTO.setMessageId(sellShopId + "");
        MessageAnnouncementSaveBO messageAnnouncementSaveBO = new MessageAnnouncementSaveBO();
        messageAnnouncementSaveBO.setType(MessageEnum.SYS_MESSAGE.getCode());
        messageAnnouncementSaveBO.setShopId(sellShopId);
        messageAnnouncementSaveBO.setTitle("催促发货");
        messageAnnouncementSaveBO.setContent("发货。。");
        messageAnnouncementSaveBO.setTextType(1);
        messageAnnouncementSaveBO.setJumpType(MessageEnum.URGE_SHIPMENTS_MESSAGE.getCode() + "");
        messageAnnouncementSaveBO.setShopType(MessageEnum.SHOP_TYPE_2.getCode());
        messageAnnouncementSaveBO.setKey(orderId + "");
        responseDTO.setData(messageAnnouncementSaveBO);
        kafkaProducerService.senMessage(JSON.toJSONString(responseDTO), MessageTopicType.COMMENT_MESSAGE_TOPIC);
    }

    @Override
    public boolean deleteOrder(Long orderId, int type) {
        return orderStatusService.updateOrderDeleteState(orderId, type);
    }

    /**
     * 生产完成
     *
     * @param orderId
     * @return
     */
    @Override
    public boolean productOver(Long orderId) {
        //修改订单状态为生产完成
        return orderStatusService.updateOrderStateByProductionState(orderId);
    }

    /**
     * 取消订单
     *
     * @param orderId 订单id
     * @param type    6买家取消、7卖家已取消
     * @return
     */
    @Override

    public Result<?> cancelOrder(Long orderId, int type, String cancelReasonId) {
        HeadParamsBO headParamsBO = CommonParameter.getHeadParamsBO();
        log.info("sessionid--------------"+headParamsBO.getSessionId());
        log.info("source--------------"+headParamsBO.getSource());
        log.info("sysuser--------------"+redisUtil.getSession(headParamsBO.getSessionId(), headParamsBO.getSource() + ""));
        SysUserDTO sysUserDTO = null;
        try {
             sysUserDTO = (SysUserDTO) redisUtil.getSession(headParamsBO.getSessionId(), headParamsBO.getSource() + "");//获取操作人
        }catch (Exception e){
        }
        OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderId);
        if (StrUtils.isNotEmpty(cancelReasonId)) {
            orderStatusDTO.setCancelOrderReasonId(Long.parseLong(cancelReasonId));
        }
        //买家取消或者卖家取消
        if (orderStatusDTO.getOrderState().equals(6) || orderStatusDTO.getOrderState().equals(7)) {
            return new Result<>(CodeEnum.ORDER_REPETITION_CANCEL);
        }
        OrderInfoDTO orderInfoDTO = this.selectById(orderId);
        if (type == 6) {
            // 发送短信
            this.sendMessage(Arrays.asList(orderInfoDTO.getSellShopId()));
            // 发送站内信
            this.sendWebMessageInChangeOrderStatus(orderInfoDTO.getSellShopId(), 2, orderId);
        } else {
            // 发送短信
            this.sendMessage(Arrays.asList(orderInfoDTO.getBuyShopId()));
            // 发送站内信
            this.sendWebMessageInChangeOrderStatus(orderInfoDTO.getBuyShopId(), 1, orderId);
        }
        //签订合同之前都可以取消订单
        //待确认
        if (orderStatusDTO.getOrderState().equals(OrderStateEnum.ORDER_STATE_ENUM_WAIT_SURE.getCode())) {
            orderStatusDTO.setOrderState(type);
            orderStatusService.updateById(orderStatusDTO);
            // 保存订单时间记录
            OrderTimeRecordSaveBO timeRecordSaveBO = new OrderTimeRecordSaveBO();
            timeRecordSaveBO.setOrderId(orderId);
            timeRecordSaveBO.setOrderState(4);
            orderTimeRecordService.add(timeRecordSaveBO);
            return new Result<>();
        }


        //待签合同
        if (orderStatusDTO.getOrderState().equals(OrderStateEnum.ORDER_STATE_ENUM_WAIT_CONTACT.getCode())) {

            if(null != sysUserDTO && sysUserDTO.getUserType() == 0){
                //未签订或者买家签订中
                if (orderStatusDTO.getContactState().equals(OrderStateEnum.ORDER_CONTACT_STATE_NO_SIGN.getCode()) || orderStatusDTO.getContactState().equals(OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGNING.getCode())) {
                    orderStatusDTO.setOrderState(type);
                    orderStatusService.updateById(orderStatusDTO);
                }
            }else {

                //未签订或者买家签订中
                if (orderStatusDTO.getContactState().equals(OrderStateEnum.ORDER_CONTACT_STATE_NO_SIGN.getCode()) || orderStatusDTO.getContactState().equals(OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGNING.getCode())) {
                    orderStatusDTO.setOrderState(type);
                    orderStatusService.updateById(orderStatusDTO);
                }
                //查询付款状态
                OrderPayRelationDTO orderPayRelationDTO = orderPayRelationService.getByOrderIdAndPeriods(orderId, 1);

                //买家已经签订或者卖家签订中
                if (orderStatusDTO.getContactState().equals(OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGN.getCode()) || orderStatusDTO.getContactState().equals(OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGNING.getCode())) {
                    //普通和询价
                    if (orderPayRelationDTO.getPayState().equals(OrderStateEnum.ORDER_PAY_STATE_PAYING.getCode())) {//支付中
                        //支付中订单 不让取消
                        return new Result<>(CodeEnum.ORDER_REPETITION_CANCEL);
                    }
                    if (orderPayRelationDTO.getPayState().equals(OrderStateEnum.ORDER_PAY_STATE_PAY_SUCCESS.getCode())) {//支付成功
                        //担保可以取消  先款不让取消
                        if (orderInfoDTO.getSellPayType().equals(1)) {//先款
                            return new Result<>(CodeEnum.ORDER_REPETITION_CANCEL);
                        }

                        //修改退款金额
                        Wrapper wrapper = new EntityWrapper();
                        wrapper.eq("order_id", orderInfoDTO.getId());
                        List<OrderCommodityRelationDTO> commodityRelationDTOList = orderCommodityRelationService.selectList(wrapper);
                        if (commodityRelationDTOList != null && commodityRelationDTOList.size() > 0) {
                            for (OrderCommodityRelationDTO orderCommodityRelationDTO : commodityRelationDTOList) {
                                OrderCommodityRelationDTO newRelationDTO = new OrderCommodityRelationDTO();
                                newRelationDTO.setId(orderCommodityRelationDTO.getId());
                                newRelationDTO.setReturnCommodityNum(orderCommodityRelationDTO.getNum());
                                newRelationDTO.setReturnCommodityMoney(orderCommodityRelationDTO.getActualMoney());
                                newRelationDTO.setPurchaseFeeMoneyScaleBackPrice(orderCommodityRelationDTO.getPurchaseFeeMoneyScalePrice());
                                orderCommodityRelationService.updateById(newRelationDTO);
                            }
                        }
                    }
                }
                //更新订单状态
                orderStatusDTO.setOrderState(type);
                orderStatusService.updateById(orderStatusDTO);
                // 保存订单时间记录
                OrderTimeRecordSaveBO timeRecordSaveBO = new OrderTimeRecordSaveBO();
                timeRecordSaveBO.setOrderId(orderId);
                timeRecordSaveBO.setOrderState(4);
                orderTimeRecordService.add(timeRecordSaveBO);

                if (orderPayRelationDTO.getPayState() == 2) {
                    //退款
                    PayOrderSaveBO payOrderSaveBO = new PayOrderSaveBO();
                    payOrderSaveBO.setIds(orderId.toString());
                    payOrderSaveBO.setPayType(0);
                    payOrderSaveBO.setType(10);
                    payService.savePay(payOrderSaveBO, false);
                }

            }
//            //退款佣金
//            if(orderStatusDTO.getCommissionMoneyPayStatus() == 2 && orderInfoDTO.getLastCommissionMoney().compareTo(BigDecimal.ZERO) > 0){
//                PayOrderSaveBO payOrderSaveBO = new PayOrderSaveBO();
//                payOrderSaveBO.setIds(orderId.toString());
//                payOrderSaveBO.setPayType(0);
//                payOrderSaveBO.setType(19);
//                payOrderSaveBO.setMoney(orderInfoDTO.getLastCommissionMoney());
//                payService.savePay(payOrderSaveBO, false);
//            }
            return new Result<>();
        }


        //待付款
        if (orderStatusDTO.getOrderState().equals(OrderStateEnum.ORDER_STATE_ENUM_WAIT_PAY.getCode())) {
            //过期 可以取消
            if (orderStatusDTO.getIsExpiration().equals(1)) {
                //更新订单状态
                orderStatusDTO.setOrderState(type);
                orderStatusService.updateById(orderStatusDTO);
                // 保存订单时间记录
                OrderTimeRecordSaveBO timeRecordSaveBO = new OrderTimeRecordSaveBO();
                timeRecordSaveBO.setOrderId(orderId);
                timeRecordSaveBO.setOrderState(4);
                orderTimeRecordService.add(timeRecordSaveBO);
                return new Result<>();
            }
        }

        return new Result<>(CodeEnum.ORDER_REPETITION_CANCEL);
    }

    /**
     * 申请维权状态
     *
     * @param orderId
     * @param type
     * @return
     */
    @Override
    public boolean updateRightsProtection(Long orderId, int type,String reason) {
        EntityWrapper<OrderRightsProtectionDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id",orderId);
        wrapper.eq("initiator",type);
        List<OrderRightsProtectionDTO> list = orderRightsProtectionService.selectList(wrapper);
        if (CustomizeUtil.listIsNotNull(list)){
            return false;
        }
        boolean b = orderStatusService.updateRightsProtection(orderId, type, 1);
        if (b) {
            return orderRightsProtectionService.addByOrderIdAndType(orderId, type, reason);//添加维权信息
        }
        return false;
    }

    /**
     * 签署完成
     *
     * @param orderId
     * @param type    1 买家签订 2卖家签订
     * @return
     */
    @Override
    public Result signOver(Long orderId, int type) {
        //如果已经签署
        OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderId);
        if (orderStatusDTO.getContactState() == type) {
            return new Result(CodeEnum.FAIL_ORDER_CONTACT_SIGN_ERROR);
        }
        return orderStatusService.contactSign(orderId, type);
    }


    @Override
    public Page<OrderInfoPageListVO> queryListPage(OrderInfoGoodsPageBO bo) {
        log.info("**************** : {}", bo);
        Page<OrderInfoPageListVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<OrderInfoPageListVO> list = null;

        //判断是否查询询盘订单
        if(null != bo.getPurchaseOrderType() && bo.getPurchaseOrderType() == BargainStateEnum.PURCHASE_ORDER_TYPE.getCode()){
            list = baseMapper.queryPurchaseListPage(page, bo);
        }else{
            list = baseMapper.queryListPage(page, bo);
        }

        //处理退换货
        if (list != null && list.size() > 0) {
            for (OrderInfoPageListVO orderInfoPageListVO : list) {
                if (orderInfoPageListVO.getOrderItem() != null && orderInfoPageListVO.getOrderItem().size() > 0) {
                    for (OrderInfoGoodsVO goodsVO : orderInfoPageListVO.getOrderItem()) {
                        Wrapper<OrderReturnCommodityDTO> wrapper = new EntityWrapper<>();
                        wrapper.eq("order_commodity_id", goodsVO.getId());
//                        wrapper.eq("is_cancel", ZERO);
                        wrapper.orderBy("create_time", false);
                        OrderReturnCommodityDTO returnCommodityDTO = orderReturnCommodityService.selectOne(wrapper);
                        if (returnCommodityDTO != null) {
                            goodsVO.setOrderReturnCommodityId(returnCommodityDTO.getId());//订单退换货表Id
                            goodsVO.setOrderReturnType(returnCommodityDTO.getType());//退换货类型
                            goodsVO.setAfterSalesState(returnCommodityDTO.getAfterSalesState());//退换货状态
                        }
                    }
                }
                // 根据订单id获取合同是否存在附件
                Wrapper<OrderContractEnclosureDTO> wrapperA = new EntityWrapper<>();
                wrapperA.eq("order_id", orderInfoPageListVO.getId());
                List<OrderContractEnclosureDTO> listA = orderContractEnclosureService.selectList(wrapperA);
                if (CustomizeUtil.listIsNotNull(listA)) {
                    orderInfoPageListVO.setIsAttachmentExists(1);
                }

                //处理票据支付
                Wrapper  wrapper = new EntityWrapper();
                wrapper.eq("order_id", orderInfoPageListVO.getId());
                wrapper.eq("pay_state", 1);
                wrapper.eq("pay_type", 2);
                OrderPayRelationDTO relationDTO = orderPayRelationService.selectOne(wrapper);
                int billPayStatus = 0;
                if(relationDTO != null){
                    billPayStatus = 1;
                    orderInfoPageListVO.setBillName(relationDTO.getBillName());
                    orderInfoPageListVO.setBillUrl(relationDTO.getBillUrl());
                }

                orderInfoPageListVO.setBillPayStatus(billPayStatus);
            }
        }
        page.setRecords(list);
        return page;
    }

    /**
     * 订单支付
     *
     * @param orderPayInfoBO
     * @return
     */
    @Transactional
    @Override
    public Result<PayOrderMotherDTO> orderPay(OrderPayInfoBO orderPayInfoBO) {
        boolean isPay = true;
        PayOrderMotherSaveBO payOrderMotherSaveBO = new PayOrderMotherSaveBO();
        BigDecimal money = new BigDecimal("0");
        Long bankId = orderPayInfoBO.getBankId();
        if (null != bankId) {
            payOrderMotherSaveBO.setBankId(bankId + "");
        }
        payOrderMotherSaveBO.setBankName(orderPayInfoBO.getBankName());
        List<OrderPayInfoRelationBO> childOrderList = new ArrayList<>();
        boolean b1 = true;
        for (String s : orderPayInfoBO.getOrderIds().split(",")) {
            if (StrUtils.isEmpty(s)) {
                isPay = false;
            }
            Long orderId = Long.parseLong(s);
            OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderId);
            Integer contactState = orderStatusDTO.getContactState();
            Integer orderState = orderStatusDTO.getOrderState();
            if (orderState != OrderStateEnum.ORDER_STATE_ENUM_WAIT_PAY.getCode() && orderState != OrderStateEnum.ORDER_STATE_ENUM_WAIT_CONTACT.getCode()) {//不是待付款并且不是待签合同
                return new Result<>(CodeEnum.ORDER_PAY_NOT_STATE);
            }
            if (contactState == OrderStateEnum.ORDER_CONTACT_STATE_NO_SIGN.getCode() || contactState == OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGNING.getCode()) {//未签订或者买家签订中
                return new Result<>(CodeEnum.ORDER_BUYER_NO_SIGN);
            }
            OrderInfoDTO orderInfoDTO = selectById(orderId);
            if (orderPayInfoBO.getPayType() == 0) {//余额支付 才回验证
                ShopInfoDTO shopInfoDTO = shopInfoService.selectById(orderInfoDTO.getBuyShopId());
                if (shopInfoDTO.getPayVerification() == 0) {//需要验证
                    if (b1) {
                        b1 = false;
                        //验证验证码是否正确
                        boolean smsCaptcha = userLoginService.getSmsCaptcha(orderPayInfoBO.getMobile(), orderPayInfoBO.getCaptcha(), 4);
                        if (!smsCaptcha) {
                            return new Result<>(CodeEnum.FAIL_Login_1004);
                        }
                    }
                }
            }

            OrderPayInfoRelationBO orderPayInfoRelationBO = new OrderPayInfoRelationBO();
            if (null != orderPayInfoBO.getBankId()) {
                orderPayInfoRelationBO.setBankId(orderPayInfoBO.getBankId() + "");//银行id
            }
            orderPayInfoRelationBO.setBankName(orderPayInfoBO.getBankName());//银行名字
            orderPayInfoRelationBO.setBusinessOrderNo(orderId + "");//订单id
            if (orderPayInfoBO.getPayType() == 0) {//余额支付
                orderPayInfoRelationBO.setMoneyUsage("余额-订单支付 订单编号：" + orderInfoDTO.getOrderNo());//资金用途
            } else {
                orderPayInfoRelationBO.setMoneyUsage("网银-订单支付 订单编号：" + orderInfoDTO.getOrderNo());//资金用途
            }

            payOrderMotherSaveBO.setPaymentUserId(orderInfoDTO.getBuyShopId());//买家店铺id
            orderPayInfoRelationBO.setReceiveUserId(orderInfoDTO.getSellShopId() + "");//卖家店铺id
            orderPayInfoRelationBO.setPaymentUserId(orderInfoDTO.getBuyShopId() + "");//买家店铺id
            int currentPayPeriods = 0;
            OrderPayRelationDTO orderPayRelationDTO = new OrderPayRelationDTO();
            List<OrderPayRelationDTO> orderPayRelationDTOList = orderPayRelationService.getByOrderId(orderId);
            for (OrderPayRelationDTO payRelationDTO : orderPayRelationDTOList) {//取出要支付的信息
                if (payRelationDTO.getPayState() == OrderStateEnum.ORDER_PAY_STATE_PAYING.getCode() || payRelationDTO.getPayState() == OrderStateEnum.ORDER_PAY_STATE_NO_PAY.getCode() ||
                        payRelationDTO.getPayState() == OrderStateEnum.ORDER_PAY_STATE_PAY_FAIL.getCode()) {
                    currentPayPeriods = payRelationDTO.getPeriods();
                    orderPayRelationDTO = payRelationDTO;
                    break;
                }
            }
            if (currentPayPeriods == 0) {
                isPay = false;
                break;
            }
            orderPayInfoRelationBO.setMoney(orderPayRelationDTO.getRealPayMoney());//金额
            money = money.add(orderPayRelationDTO.getRealPayMoney());
            orderPayInfoRelationBO.setBusinessOrderWaterNo(orderPayRelationDTO.getId() + "");
//            if (orderInfoDTO.getSellPayType() == 0) {//担保交易
//                orderPayInfoRelationBO.setTrsFlag("B00");
//                if (orderInfoDTO.getPayType() != 0) {//预售
//                    if (currentPayPeriods == 1) {//现货第一期 支付佣金
//                        orderPayInfoRelationBO.setTrsFlag("A00");
//                    }
//                }
//            } else {//先款交易
//                orderPayInfoRelationBO.setTrsFlag("A00");
//                if (orderInfoDTO.getPayType() == 0) {//现货
//                    if (currentPayPeriods == 1) {//现货第一期 支付佣金
//                        orderPayRelationService.payOrderFirstCommission(orderId);
//                    }
//                } else {//预售
//                    if (currentPayPeriods == 2) {//预售是第二期 支付佣金
//                        orderPayRelationService.payOrderFirstCommission(orderId);
//                    }
//                }
//            }

            if (orderInfoDTO.getSellPayType() == 0) {//担保交易
                orderPayInfoRelationBO.setTrsFlag("B00");
            } else {//先款交易
                if(currentPayPeriods == 2){
                    orderPayInfoRelationBO.setTrsFlag("A00");
                } else {
                    orderPayInfoRelationBO.setTrsFlag("B00");
                }
            }
            childOrderList.add(orderPayInfoRelationBO);
            //支付状态变为支付中
            //orderPayRelationDTO.setPayState(OrderStateEnum.ORDER_PAY_STATE_PAYING.getCode());
            //orderPayRelationService.updateById(orderPayRelationDTO);
        }
        if (!isPay) {
            return new Result<>(CodeEnum.FAIL_200026);
        }
        payOrderMotherSaveBO.setMoney(money);
        //payOrderMotherSaveBO.setTrsFlag("B00");//收款方收款成功后，再冻结资金
//        payOrderMotherSaveBO.setPayType(0);//0普通订单
        String s = JSON.toJSONString(childOrderList);
        payOrderMotherSaveBO.setChildOrderList(s);
        // 更新es商品
        String[] orderIds = orderPayInfoBO.getOrderIds().split(",");
        for (String orderId : orderIds) {
            this.updateEsGoods(Long.valueOf(orderId));
        }
        if (orderPayInfoBO.getPayType() == 0) {//余额支付
//            return payOrderService.saveBalancePay(payOrderMotherSaveBO);
        }
        //网银支付
        return payOrderService.saveOnlineBankPay(payOrderMotherSaveBO);
    }

//    /**
//     * 订单支付成功
//     *
//     * @param orderId
//     * @return
//     */
//    @Override
//    public boolean updatePaySuccess(Long orderId) {
//        log.info("orderid-------"+orderId+"--------待发货倒计时0----------");
//        Date currentDateTime = DateUtils.getCurrentDateTime();//当前时间
//        OrderInfoDTO orderInfoDTO = selectById(orderId);
//        int type = orderInfoDTO.getPayType();
//        int currentPayPeriods = 0;
//        OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderId);
//        OrderPayRelationDTO orderPayRelationDTO = new OrderPayRelationDTO();
//        List<OrderPayRelationDTO> orderPayRelationDTOList = orderPayRelationService.getByOrderId(orderId);
//        for (OrderPayRelationDTO payRelationDTO : orderPayRelationDTOList) {
//            if (payRelationDTO.getPayState() == OrderStateEnum.ORDER_PAY_STATE_NO_PAY.getCode() ||
//                    payRelationDTO.getPayState() == OrderStateEnum.ORDER_PAY_STATE_PAY_FAIL.getCode()) {
//                currentPayPeriods = payRelationDTO.getPeriods();
//                orderPayRelationDTO = payRelationDTO;
//                break;
//            }
//            if (payRelationDTO.getPayState() == OrderStateEnum.ORDER_PAY_STATE_PAYING.getCode()) {
//                return false;
//            }
//        }
//        if (currentPayPeriods == 0) {
//            return false;
//        }
//        if (currentPayPeriods == 2) {//预售付尾款
//            //更新倒计时
//            OrderExpirationDateDTO orderExpirationDateDTO = orderExpirationDateService.getByOrderId(orderId);
//            SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.WAIT_DELIVER_GOODS);//卖家签订合同后倒计时
//            Date expireTime = DateUtils.addDay(currentDateTime, Integer.parseInt(sysDictDTO.getValue()));//过期时间
//            orderExpirationDateDTO.setExpirationTime(expireTime);
//            orderExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode());
//            orderExpirationDateService.updateByOrderId(orderExpirationDateDTO);//更新倒计时
//            String tiem = DateUtils.dateToStr(expireTime);
//            log.info("orderid-------"+orderId+"--------待发货倒计时1----------"+tiem+"---------天数-----"+sysDictDTO.getValue());
//            //变为待发货
//            orderStatusDTO.setOrderState(OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode());
//            boolean b = orderStatusService.updateById(orderStatusDTO);
//            if (b) {
//                //发送短信
//                try {
//                    sendMessage(Arrays.asList(orderInfoDTO.getSellShopId()));
//                } catch (Exception e) {
//                    log.error("发送短信失败");
//                    e.printStackTrace();
//                }
//                //发送站内信
//                try {
//                    sendWebMessageInChangeOrderStatus(orderInfoDTO.getSellShopId(), 2, orderId);
//                } catch (Exception e) {
//                    log.error("发送站内信失败");
//                    e.printStackTrace();
//                }
//
//                //支付状态为已支付
//                orderPayRelationDTO.setPayState(OrderStateEnum.ORDER_PAY_STATE_PAY_SUCCESS.getCode());
//                orderProcessLogService.addByOrderInfo(orderId, OrderStateEnum.ORDER_PAY_SUCCESS.getCode());//添加订单日志表
//                return orderPayRelationService.updateById(orderPayRelationDTO);
//            }
//            return false;
//        }
//        //现货或者预售付收款
//        if (type == 0) {//现货
//            //卖家签订合同
//            if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGN.getCode()) {
//                //更新倒计时
//                OrderExpirationDateDTO orderExpirationDateDTO = orderExpirationDateService.getByOrderId(orderId);
//                SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.WAIT_DELIVER_GOODS);//卖家签订合同后倒计时
//                Date expireTime = DateUtils.addDay(currentDateTime, Integer.parseInt(sysDictDTO.getValue()));//过期时间
//                orderExpirationDateDTO.setExpirationTime(expireTime);
//                orderExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode());
//                orderExpirationDateService.updateByOrderId(orderExpirationDateDTO);//更新倒计时
//
//                String tiem = DateUtils.dateToStr(expireTime);
//                log.info("orderid-------"+orderId+"--------待发货倒计时2----------"+tiem+"---------天数-----"+sysDictDTO.getValue());
//                //添加订单日志表
//                orderProcessLogService.addByOrderInfo(orderId, OrderStateEnum.ORDER_PAY_SUCCESS.getCode());
//                //变为待发货
//                orderStatusDTO.setOrderState(OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode());
//
//                //发送短信
//                try {
//                    sendMessage(Arrays.asList(orderInfoDTO.getSellShopId()));
//                } catch (Exception e) {
//                    log.error("发送短信失败");
//                    e.printStackTrace();
//                }
//                //发送站内信
//                try {
//                    sendWebMessageInChangeOrderStatus(orderInfoDTO.getSellShopId(), 2, orderId);
//                } catch (Exception e) {
//                    log.error("发送站内信失败");
//                    e.printStackTrace();
//                }
//                return orderStatusService.updateById(orderStatusDTO);
//            }
//            //变为生产完成
//            orderStatusDTO.setGoodsProductionState(OrderStateEnum.ORDER_GOODS_PRO_OVER.getCode());
//        }
//        if (type == 1) {//分批
//            //变为生产中
//            orderStatusDTO.setGoodsProductionState(OrderStateEnum.ORDER_GOODS_PRO_ING.getCode());
//            log.info("orderid-------"+orderId+"--------待发货倒计时3----------");
//        }
//        orderStatusService.updateById(orderStatusDTO);//更新状态
//        //分分批和现货 卖家未签合同
//        //支付状态为已支付
//        orderPayRelationDTO.setPayState(OrderStateEnum.ORDER_PAY_STATE_PAY_SUCCESS.getCode());
//        return orderPayRelationService.updateById(orderPayRelationDTO);
//    }

    @Override
    public List<OrderInfoSalesVO> querySalesList(Long shopId, String startDate, String endDate) {
        return baseMapper.querySalesList(shopId, startDate, endDate);
    }

    /**
     * 跳转待支付页面
     *
     * @param orderIds
     * @return
     */
    @Override
    public OrderPayPageVO getSkipPay(String orderIds) {
        OrderPayPageVO orderPayPageVO = new OrderPayPageVO();
        BigDecimal allMoney = new BigDecimal("0");
        List<String> noSignOrderNoIdList = new ArrayList<>();//未签署的订单编号
        List<Long> signOrderIdList = new ArrayList<>();//签署的订单idList
        String[] orderIdList = orderIds.split(",");
        Long buyShopId = 0L;
        for (String s : orderIdList) {
            Long orderId = Long.parseLong(s);
            OrderInfoDTO orderInfoDTO = selectById(orderId);
            buyShopId = orderInfoDTO.getBuyShopId();
            OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderId);
            if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_NO_SIGN.getCode() ||
                    orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGNING.getCode()) {
                noSignOrderNoIdList.add(orderInfoDTO.getOrderNo());
            }
            if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGN.getCode() ||
                    orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGN.getCode() ||
                    orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGNING.getCode()) {
                orderPayPageVO.setSkip(true);
                signOrderIdList.add(orderStatusDTO.getOrderId());
            }
            allMoney = allMoney.add(orderInfoDTO.getActualMoney());
        }
        orderPayPageVO.setAllPrice(allMoney);
        orderPayPageVO.setNoSignOrderNoIdList(noSignOrderNoIdList);
        orderPayPageVO.setSignOrderIdList(signOrderIdList);

        ShopInfoDTO shopInfoDTO = shopInfoService.selectById(buyShopId);
        orderPayPageVO.setIsAuth(shopInfoDTO.getPayVerification() + "");
        orderPayPageVO.setAuthPhNumber(shopInfoDTO.getPayMobile());

        return orderPayPageVO;
    }

    @Override
    public Map<String, Object> getPayInfoByOrderIds(String orderIds) {
        Map<String, Object> map = new HashMap<>();
        // 订单全部金额
        BigDecimal allMoney = new BigDecimal("0");
        // 订单是否存在分期订单,0没有，1有
        int isCheckOrder = 0;
        int periods = 0;
        int overPeriods = 0;
        String[] orderIdList = orderIds.split(",");
        for (String s : orderIdList) {
            Long orderId = Long.parseLong(s);
            //价格取订单支付表价格
            List<OrderPayRelationDTO> orderPayRelationDTOList = orderPayRelationService.getByOrderId(orderId);
            for (OrderPayRelationDTO orderPayRelationDTO : orderPayRelationDTOList) {
                periods = orderPayRelationDTO.getPeriods();

                //未支付或者支付失败
                if (orderPayRelationDTO.getPayState() == OrderStateEnum.ORDER_PAY_STATE_NO_PAY.getCode() ||
                        orderPayRelationDTO.getPayState() == OrderStateEnum.ORDER_PAY_STATE_PAY_FAIL.getCode()) {
                    allMoney = allMoney.add(orderPayRelationDTO.getRealPayMoney());
                    break;
                }

            }
            // 获取订单类型
            OrderInfoDTO selectById = this.selectById(orderId);
            if (selectById.getPayType() == 1) {
                isCheckOrder = 1;
                overPeriods = periods;
            }
        }
        map.put("periods", overPeriods);
        map.put("allMoney", allMoney);
        map.put("isCheckOrder", isCheckOrder);
        return map;
    }

    @Override
    public List<OrderContractVO> getOrderContarctInfo(Long shopId, String orderIds, int type, int signType) {
        List<OrderContractVO> orderContractVOList = new ArrayList<>();
        String[] orderArr = orderIds.split(",");
        for (String s : orderArr) {
            Long orderId = Long.parseLong(s);
            OrderContractVO orderContractVO = new OrderContractVO();
            OrderInfoDTO orderInfoDTO = selectById(orderId);
            OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderId);
            //判断用户是否设置了赊销类型
            ShopContractParamRelationDTO  shopContractParamRelationDTO = orderContractParamRelationService.getContractContent(orderId);
            if(null == shopContractParamRelationDTO){
                shopContractParamRelationDTO = shopContractParamRelationService.getByShopIdAndType(orderInfoDTO.getSellShopId(), orderInfoDTO.getPayType());
            }
            String signaturePage = orderContractRelationService.getSignaturePage(orderId, shopId, type, orderIds, null);

            orderContractVO.setOrderId(orderId);
            orderContractVO.setOrderNo(orderInfoDTO.getOrderNo());
            orderContractVO.setContactName(shopContractParamRelationDTO.getContractName());
            orderContractVO.setOrderMoney(orderInfoDTO.getActualMoney());
            orderContractVO.setContactUrl(signaturePage);
            orderContractVO.setContractState(orderStatusDTO.getContactState());
            orderContractVO.setSignPlayerType(signType);
            orderContractVO.setPurchaseOrderType(orderInfoDTO.getPurchaseOrderType());
            orderContractVOList.add(orderContractVO);
        }
        return orderContractVOList;
    }

    private  int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        smdate=sdf.parse(sdf.format(smdate));
        bdate=sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    @Override
    public Page<OrderInfoPageListVO> queryAdminListPage(OrderAdminListBO bo) {
        Page<OrderInfoPageListVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<OrderInfoPageListVO> list = null;
        //判断是否查询询盘订单
        if(null != bo.getPurchaseOrderType() && bo.getPurchaseOrderType() == BargainStateEnum.PURCHASE_ORDER_TYPE.getCode()){
            list = baseMapper.queryPurchaseAdminListPage(page, bo);
        }else{
            list = baseMapper.queryAdminListPage(page, bo);
        }


        if (!isNull(list)) {
            for (OrderInfoPageListVO pageListVO : list) {
                OrderDetailsHeaderVO headerVO = baseMapper.queryOrderDetailsHeaders(pageListVO.getId());
                if (headerVO!=null){
                    try {
                        if (headerVO.getDeadlineForSellerToSign()!=null){
                            //待卖家合同签订截至时间
                            int i = this.daysBetween(DateUtils.getCurrentDateTime(),headerVO.getDeadlineForSellerToSign());
                            if (i<0){
                                pageListVO.setSignStatus(1);
                            }else {
                                pageListVO.setSignStatus(0);
                            }
                        }else {
                            pageListVO.setSignStatus(0);
                        }
                        //待收款支付截至时间deadlineForPayment,twoExpectPaymentDeadline
                       // int j=0;
                        int k=0;
                        pageListVO.setPayStatus(0);
                        if (headerVO.getDeadlineForPayment()!=null && headerVO.getFirstPaymentTime()==null){
                          int  j = this.daysBetween(DateUtils.getCurrentDateTime(),headerVO.getDeadlineForPayment());
                          if (j<0){
                              k=k+1;
                          }
                        }
                        if (headerVO.getDeadlineForPayment()!=null && headerVO.getFirstPaymentTime()!=null){
                            int j = this.daysBetween(headerVO.getFirstPaymentTime(),headerVO.getDeadlineForPayment());
                            if (j<0){
                                k=k+1;
                            }
                        }

                        if (headerVO.getTwoExpectPaymentDeadline()!=null && headerVO.getFinalPaymentTime()==null){
                            int j = this.daysBetween(DateUtils.getCurrentDateTime(),headerVO.getTwoExpectPaymentDeadline());
                            if (j<0){
                                k=k+1;
                            }
                        }

                        if (headerVO.getTwoExpectPaymentDeadline()!=null && headerVO.getFinalPaymentTime()!=null){
                            int j = this.daysBetween( headerVO.getFinalPaymentTime(),headerVO.getTwoExpectPaymentDeadline());
                            if (j<0){
                                k=k+1;
                            }
                        }


                        if ( k>0){
                            pageListVO.setPayStatus(1);
                        }else {
                            pageListVO.setPayStatus(0);
                        }

                        //备货截至时间sockDeadlineTime
                        if (headerVO.getSockDeadlineTime()!=null){
                            int i = this.daysBetween(DateUtils.getCurrentDateTime(),headerVO.getSockDeadlineTime());
                            if (i<0){
                                pageListVO.setReadyStatus(1);
                            }else {
                                pageListVO.setReadyStatus(0);
                            }
                        }else {
                            pageListVO.setReadyStatus(0);
                        }
                        //发货截至时间deadlineToBeShipped
                        if (headerVO.getDeadlineToBeShipped()!=null){
                            int i = this.daysBetween(DateUtils.getCurrentDateTime(),headerVO.getDeadlineToBeShipped());
                            if (i<0){
                                pageListVO.setSendStatus(1);
                            }else {
                                pageListVO.setSendStatus(0);
                            }
                        }else {
                            pageListVO.setSendStatus(0);
                        }
                        //签收截至时间deadlineToBeSigned
                        if (headerVO.getDeadlineToBeSigned()!=null){
                            int i = this.daysBetween(DateUtils.getCurrentDateTime(),headerVO.getDeadlineToBeSigned());
                            if (i<0){
                                pageListVO.setReciveStatus(1);
                            }else {
                                pageListVO.setReciveStatus(0);
                            }
                        }else {
                            pageListVO.setReciveStatus(0);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                //赊销支付时间是否过期
                if (pageListVO.getOrderPaymentTypeVOItem()!=null){
                    for (OrderPaymentTypeVO orderPaymentTypeVO : pageListVO.getOrderPaymentTypeVOItem()) {
                        if (orderPaymentTypeVO.getType()==1 && orderPaymentTypeVO.getPaymentType()==2){
                            try {
                                if (pageListVO.getPaymentExpireDate()==null){
                                    pageListVO.setPayStatus(0);
                                }else {
                                    int  j = this.daysBetween(DateUtils.getCurrentDateTime(),pageListVO.getPaymentExpireDate());
                                    if (j<=0){
                                        pageListVO.setPayStatus(1);
                                    }else {
                                        pageListVO.setPayStatus(0);
                                    }
                                }

                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                }

                if (!isNull(pageListVO.getOrderItem())) {
                    for (OrderInfoGoodsVO orderGoods : pageListVO.getOrderItem()) {
                        String logUrl = orderGoods.getLogUrl ();
                        if (StringUtils.isEmpty (logUrl)) {
                            orderGoods.setLogUrl (orderGoods.getPurchaseCommodityUrl ());
                        }
                    }
                    int goodsNum = 0;
                    for (OrderInfoGoodsVO goodsVO : pageListVO.getOrderItem()) {
                        goodsNum += goodsVO.getNum();
                        // 处理商品链接
                        String goodsUrl = GOODS_URL + goodsVO.getCommodityId() + "&type=0";
                        goodsVO.setGoodsUrl(goodsUrl);
                        // 获取订单商品售后表id
                        Wrapper<OrderReturnCommodityDTO> wrapper = new EntityWrapper<>();
                        wrapper.eq("order_commodity_id", goodsVO.getId());
                        OrderReturnCommodityDTO selectOne = orderReturnCommodityService.selectOne(wrapper);
                        if (selectOne != null) {
                            goodsVO.setOrderReturnCommodityId(selectOne.getId());
                        }
                    }
                    pageListVO.setGoodsNum(goodsNum);
                }
                List<PayOrderLogDTO> payOrderLogDTOS=null;
                EntityWrapper<PayOrderLogDTO> objectEntityWrapper = new EntityWrapper<>();
                objectEntityWrapper.eq("order_id",pageListVO.getId());
                objectEntityWrapper.in("type","1,19");
                payOrderLogDTOS = payOrderLogService.selectList(objectEntityWrapper);
                pageListVO.setPayOrderLogDTOList(payOrderLogDTOS);

            }
        }
        page.setRecords(list);
        return page;
    }


    @Override
    public Page<OrderInfoPageListVO> queryDealOrderListPage(OrderAdminListBO bo) {
        Page<OrderInfoPageListVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        //线上订单交易明细
        List<OrderInfoPageListVO> list = baseMapper.queryDealOrderListPage(page, bo);
        BigDecimal total = BigDecimal.ZERO;
        for(OrderInfoPageListVO vo : list){
              total =  total.add(vo.getCurrentStall());
        }
        for(OrderInfoPageListVO vo : list){
            vo.setLastCommissionMoney(total);
        }
        page.setRecords(list);

        return page;
    }

    @Override
    public Page<OrderValetPlaceVO> queryValetPlaceOrderList(OrderValetPlaceBO bo) {
        Page<OrderValetPlaceVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<OrderValetPlaceVO> list = baseMapper.queryValetPlaceOrderList(page, bo);
        page.setRecords(list);
        return page;
    }

    @Override
    public List<OrderLogisticsVO> queryAdvanceOrderList(Long lastNo) {
        Page<OrderLogisticsVO> page = new Page<>(1, 50);
        return baseMapper.queryAdvanceOrderList(page, lastNo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<OrderContractVO> newSureOrder(String orderIds, Long signShopId, int type, List<byte[]> bytes, String annex) {
        log.info("确认订单时附件对象:{}", annex);
        List<String> orderIdList = Arrays.asList(orderIds.split(","));
        List<OrderContractVO> orderContractVOList = new ArrayList<>();
        for (int i = 0; i < orderIdList.size(); i++) {
            Long orderId = Long.parseLong(orderIdList.get(i));
            if (CustomizeUtil.strIsNull(annex)) {
                OrderContractVO orderContractVO = this.sureOrder(orderId, signShopId, type, bytes.get(i), orderIds, "");
                orderContractVOList.add(orderContractVO);
            } else {
                List<OrderSureBO> list = JSONArray.parseArray(annex, OrderSureBO.class);
                for (OrderSureBO bo : list) {
                    if (bo.getOrderId().equals(orderId)) {
                        OrderContractVO orderContractA = this.sureOrder(orderId, signShopId, type, bytes.get(i), orderIds, bo.getContractAttachments());
                        orderContractVOList.add(orderContractA);
                    }
                }
            }
        }
        return orderContractVOList;
    }

    @Override
    public List<ExportAdminOrderListVO> queryExportAdminOrderList(Long shopId, String ids, Integer status) {
        try {
            // 状态为10查询全部，否则根据订单状态查询
            if ("0".equals(ids)) {
                if (status.equals(10)) {
                    List<ExportAdminOrderListQueryVO> queryList = baseMapper.queryExportAdminOrderList(shopId, null, 10,0);
                    return this.getQuery(queryList);
                }
                // 根据订单状态查询
                List<ExportAdminOrderListQueryVO> list = baseMapper.queryExportAdminOrderList(shopId, null, status,0);
                return this.getQuery(list);
            }
            List<ExportAdminOrderListVO> result = new ArrayList<>();
            String[] idArray = ids.split(",");
            for (String id : idArray) {
                // 根据id查询
                List<ExportAdminOrderListQueryVO> list = baseMapper.queryExportAdminOrderList(shopId, Long.valueOf(id), 10,0);
                List<ExportAdminOrderListVO> query = this.getQuery(list);
                result.addAll(query);
            }
            return result;
        } catch (Exception e) {
            log.error("订单导出报错信息:{}", e.getMessage());
            e.printStackTrace();
        }
        return this.getQuery(null);
    }

    @Override
    public List<ExportAdminOrderListVO> queryExportAdminOrderList(OrderAdminListBO bo) {
        try {
            // 状态为0查询全部，否则根据订单状态查询
            if (bo.getIds()==null) {
                // 根据订单状态查询
                List<ExportAdminOrderListQueryVO> list = baseMapper.queryExportAdminOrderList1(bo);

                List<ExportAdminOrderListQueryVO>  exList= new ArrayList<>();
                Map<String, List<ExportAdminOrderListQueryVO>> collect = list.stream().collect(Collectors.groupingBy(ExportAdminOrderListQueryVO::getOrderNumber));
                for (String s : collect.keySet()) {
                    List<ExportAdminOrderListQueryVO> exportAdminOrderListQueryVOS = collect.get(s);
                    if (CustomizeUtil.listIsNotNull(exportAdminOrderListQueryVOS)){
                        boolean flag=false;
                        for (ExportAdminOrderListQueryVO exportAdminOrderListQueryVO : exportAdminOrderListQueryVOS) {
                            if (exportAdminOrderListQueryVO.getDeliveryTime()==null){
                                flag=true;
                            }
                        }
                        if (flag){
                            exList.addAll(exportAdminOrderListQueryVOS);
                        }else {
                            Map<Date, List<ExportAdminOrderListQueryVO>> collect1 = exportAdminOrderListQueryVOS.stream().collect(Collectors.groupingBy(ExportAdminOrderListQueryVO::getDeliveryTime));
                            if (collect1.size()>1){
                                int a=0;
                                for (Date date : collect1.keySet()) {
                                    if (a==0){
                                        List<ExportAdminOrderListQueryVO> listQueryVOS = collect1.get(date);
                                        exList.addAll(listQueryVOS);
                                    }else {
                                        List<ExportAdminOrderListQueryVO> listQueryVOS = collect1.get(date);
                                        if (CustomizeUtil.listIsNotNull(listQueryVOS)){
                                            for (int i = 0; i < listQueryVOS.size(); i++) {
                                                ExportAdminOrderListQueryVO exportAdminOrderListQueryVO = listQueryVOS.get(i);
                                                exportAdminOrderListQueryVO.setCommission(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setChangePriceDiscount(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setEstimateCommission(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setMemberDiscount(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setPurchaseFeeMoney(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setPurchaseFeeMoneyScalePrice(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setRefundAmount(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setScaleBackPrice(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setTheAmountActuallyPaid(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setTotalCommodityPrice(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setUnitPrice(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setWholesaleDiscount(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setActuallyMoney(new BigDecimal("0.00"));
                                            }
                                        }
                                        exList.addAll(listQueryVOS);
                                    }
                                    a=a+1;
                                }
                            }else {
                                for (Date date : collect1.keySet()) {
                                    List<ExportAdminOrderListQueryVO> listQueryVOS = collect1.get(date);
                                    exList.addAll(listQueryVOS);
                                }
                            }
                        }
                    }
                }
                List<ExportAdminOrderListQueryVO> collect1 = exList.stream().sorted(Comparator.comparing(ExportAdminOrderListQueryVO::getOrderTime).reversed()).collect(Collectors.toList());

                List<ExportAdminOrderListVO> query = this.getQuery(collect1);
                //计算实付金额
                if (CustomizeUtil.listIsNotNull(query)){
                    for (ExportAdminOrderListVO vo : query) {
                        if (vo.getTheAmountActuallyPaid()!=null){
                            if (vo.getRefundAmount()!=null){
                                vo.setActuallyMoney(vo.getTheAmountActuallyPaid().subtract(vo.getRefundAmount()));
                            }else {
                                vo.setActuallyMoney(vo.getTheAmountActuallyPaid());
                            }
                        }else {
                            vo.setActuallyMoney(new BigDecimal("0.00"));
                        }
                    }
                }
                return query;
            }
            List<ExportAdminOrderListVO> result = new ArrayList<>();

            String[] idArray = bo.getIds().split(",");
            for (String id : idArray) {
                // 根据id查询

                List<ExportAdminOrderListQueryVO> list = baseMapper.queryExportAdminOrderListById(id);
                List<ExportAdminOrderListQueryVO>  exList= new ArrayList<>();
                if (CustomizeUtil.listIsNotNull(list)){
                    boolean flag=false;
                    for (ExportAdminOrderListQueryVO exportAdminOrderListQueryVO : list) {
                        if (exportAdminOrderListQueryVO.getDeliveryTime()==null){
                            flag=true;
                        }
                    }
                    if (flag){
                        List<ExportAdminOrderListVO> query = this.getQuery(list);
                        result.addAll(query);
                    }else {
                        Map<Date, List<ExportAdminOrderListQueryVO>> collect = list.stream().collect(Collectors.groupingBy(ExportAdminOrderListQueryVO::getDeliveryTime));
                        if (collect.size()>1){
                            int a=0;
                            for (Date date : collect.keySet()) {
                                if (a==0){
                                    List<ExportAdminOrderListQueryVO> listQueryVOS = collect.get(date);
                                    exList.addAll(listQueryVOS);
                                }else {
                                    List<ExportAdminOrderListQueryVO> listQueryVOS = collect.get(date);
                                    if (CustomizeUtil.listIsNotNull(listQueryVOS)){
                                        for (int i = 0; i < listQueryVOS.size(); i++) {
                                            ExportAdminOrderListQueryVO exportAdminOrderListQueryVO = listQueryVOS.get(i);
                                            exportAdminOrderListQueryVO.setCommission(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setChangePriceDiscount(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setEstimateCommission(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setMemberDiscount(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setPurchaseFeeMoney(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setPurchaseFeeMoneyScalePrice(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setRefundAmount(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setScaleBackPrice(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setTheAmountActuallyPaid(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setTotalCommodityPrice(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setUnitPrice(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setWholesaleDiscount(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setActuallyMoney(new BigDecimal("0.00"));
                                        }
                                    }
                                    exList.addAll(listQueryVOS);
                                }
                                a=a+1;
                            }
                            List<ExportAdminOrderListVO> query = this.getQuery(exList);
                            result.addAll(query);

                        }else {
                            for (Date date : collect.keySet()) {
                                List<ExportAdminOrderListQueryVO> listQueryVOS = collect.get(date);
                                List<ExportAdminOrderListVO> query = this.getQuery(listQueryVOS);
                                result.addAll(query);
                            }
                        }
                    }
                }

            }
             //result.stream().sorted(Comparator.comparing(ExportAdminOrderListVO::getOrderTime).reversed()).collect(Collectors.toList());
            if (CustomizeUtil.listIsNotNull(result)){
                //计算实付金额
                if (CustomizeUtil.listIsNotNull(result)){
                    for (ExportAdminOrderListVO vo : result) {
                        if (vo.getTheAmountActuallyPaid()!=null){
                            if (vo.getRefundAmount()!=null){
                                vo.setActuallyMoney(vo.getTheAmountActuallyPaid().subtract(vo.getRefundAmount()));
                            }else {
                                vo.setActuallyMoney(vo.getTheAmountActuallyPaid());
                            }
                        }else {
                            vo.setActuallyMoney(new BigDecimal("0.00"));
                        }
                    }
                }
            }
            return result;
        } catch (Exception e) {
            log.error("订单导出报错信息:{}", e.getMessage());
            e.printStackTrace();
        }
        return this.getQuery(null);
    }

    @Override
    public List<ExportAdminOrderListVO> queryExportAdminOrderList(Long shopId, String ids, Integer status, Integer purchaseOrderType) {
        try {
            // 状态为10查询全部，否则根据订单状态查询
            if ("0".equals(ids)) {
                if (status.equals(10)) {
                    List<ExportAdminOrderListQueryVO> queryList = baseMapper.queryExportAdminOrderList(shopId, null, 10,purchaseOrderType);

                    return this.getQuery(queryList);
                }
                // 根据订单状态查询
                List<ExportAdminOrderListQueryVO> list = baseMapper.queryExportAdminOrderList(shopId, null, status,purchaseOrderType);
                return this.getQuery(list);
            }
            List<ExportAdminOrderListVO> result = new ArrayList<>();
            String[] idArray = ids.split(",");
            for (String id : idArray) {
                // 根据id查询
                List<ExportAdminOrderListQueryVO> list = baseMapper.queryExportAdminOrderList(shopId, Long.valueOf(id), 10,purchaseOrderType);
                List<ExportAdminOrderListVO> query = this.getQuery(list);
                result.addAll(query);
            }
            return result;
        } catch (Exception e) {
            log.error("订单导出报错信息:{}", e.getMessage());
            e.printStackTrace();
        }
        return this.getQuery(null);
    }

    @Override
    public List<ExportSellerOrderListVO> queryExportSellerOrderList(Long shopId, String ids, Integer status,Integer purchaseOrderType) {
        try {
            // 状态为10查询全部，否则根据订单状态查询
            if ("0".equals(ids)) {
                if (status.equals(10)) {
                    List<ExportSellerOrderListQueryVO> queryList = baseMapper.queryExportSellerOrderList(shopId, null, 10,purchaseOrderType);
                    List<ExportSellerOrderListQueryVO>  exList= new ArrayList<>();
                    Map<String, List<ExportSellerOrderListQueryVO>> collect = queryList.stream().collect(Collectors.groupingBy(ExportSellerOrderListQueryVO::getOrderNumber));
                    for (String s : collect.keySet()) {
                        List<ExportSellerOrderListQueryVO> exportAdminOrderListQueryVOS = collect.get(s);
                        if (CustomizeUtil.listIsNotNull(exportAdminOrderListQueryVOS)){
                            boolean flag=false;
                            for (ExportSellerOrderListQueryVO exportAdminOrderListQueryVO : exportAdminOrderListQueryVOS) {
                                if (exportAdminOrderListQueryVO.getDeliveryTime()==null){
                                    flag=true;
                                }
                            }
                            if (flag){
                                exList.addAll(exportAdminOrderListQueryVOS);
                            }else {
                                Map<Date, List<ExportSellerOrderListQueryVO>> collect1 = exportAdminOrderListQueryVOS.stream().collect(Collectors.groupingBy(ExportSellerOrderListQueryVO::getDeliveryTime));
                                if (collect1.size()>1){
                                    int a=0;
                                    for (Date date : collect1.keySet()) {
                                        if (a==0){
                                            List<ExportSellerOrderListQueryVO> listQueryVOS = collect1.get(date);
                                            exList.addAll(listQueryVOS);
                                        }else {
                                            List<ExportSellerOrderListQueryVO> listQueryVOS = collect1.get(date);
                                            if (CustomizeUtil.listIsNotNull(listQueryVOS)){
                                                for (int i = 0; i < listQueryVOS.size(); i++) {
                                                    ExportSellerOrderListQueryVO exportAdminOrderListQueryVO = listQueryVOS.get(i);
                                                    exportAdminOrderListQueryVO.setCommission(new BigDecimal("0.00"));
                                                    exportAdminOrderListQueryVO.setChangePriceDiscount(new BigDecimal("0.00"));
                                                    exportAdminOrderListQueryVO.setEstimateCommission(new BigDecimal("0.00"));
                                                    exportAdminOrderListQueryVO.setMemberDiscount(new BigDecimal("0.00"));
                                                  //  exportAdminOrderListQueryVO.setPurchaseFeeMoney(new BigDecimal("0.00"));
                                                   // exportAdminOrderListQueryVO.setPurchaseFeeMoneyScalePrice(new BigDecimal("0.00"));
                                                    exportAdminOrderListQueryVO.setRefundAmount(new BigDecimal("0.00"));
                                                  //  exportAdminOrderListQueryVO.setScaleBackPrice(new BigDecimal("0.00"));
                                                    exportAdminOrderListQueryVO.setTheAmountActuallyPaid(new BigDecimal("0.00"));
                                                    exportAdminOrderListQueryVO.setTotalCommodityPrice(new BigDecimal("0.00"));
                                                    exportAdminOrderListQueryVO.setUnitPrice(new BigDecimal("0.00"));
                                                    exportAdminOrderListQueryVO.setWholesaleDiscount(new BigDecimal("0.00"));
                                                }
                                            }
                                            exList.addAll(listQueryVOS);
                                        }
                                        a=a+1;
                                    }
                                }else {
                                    for (Date date : collect1.keySet()) {
                                        List<ExportSellerOrderListQueryVO> listQueryVOS = collect1.get(date);
                                        exList.addAll(listQueryVOS);
                                    }
                                }
                            }
                        }
                    }
                    return this.getSellerQuery(queryList);
                }
                // 根据订单状态查询
                List<ExportSellerOrderListQueryVO> list = baseMapper.queryExportSellerOrderList(shopId, null, status,purchaseOrderType);
                List<ExportSellerOrderListQueryVO>  exList= new ArrayList<>();
                Map<String, List<ExportSellerOrderListQueryVO>> collect = list.stream().collect(Collectors.groupingBy(ExportSellerOrderListQueryVO::getOrderNumber));
                for (String s : collect.keySet()) {
                    List<ExportSellerOrderListQueryVO> exportAdminOrderListQueryVOS = collect.get(s);
                    if (CustomizeUtil.listIsNotNull(exportAdminOrderListQueryVOS)){
                        boolean flag=false;
                        for (ExportSellerOrderListQueryVO exportAdminOrderListQueryVO : exportAdminOrderListQueryVOS) {
                            if (exportAdminOrderListQueryVO.getDeliveryTime()==null){
                                flag=true;
                            }
                        }
                        if (flag){
                            exList.addAll(exportAdminOrderListQueryVOS);
                        }else {
                            Map<Date, List<ExportSellerOrderListQueryVO>> collect1 = exportAdminOrderListQueryVOS.stream().collect(Collectors.groupingBy(ExportSellerOrderListQueryVO::getDeliveryTime));
                            if (collect1.size()>1){
                                int a=0;
                                for (Date date : collect1.keySet()) {
                                    if (a==0){
                                        List<ExportSellerOrderListQueryVO> listQueryVOS = collect1.get(date);
                                        exList.addAll(listQueryVOS);
                                    }else {
                                        List<ExportSellerOrderListQueryVO> listQueryVOS = collect1.get(date);
                                        if (CustomizeUtil.listIsNotNull(listQueryVOS)){
                                            for (int i = 0; i < listQueryVOS.size(); i++) {
                                                ExportSellerOrderListQueryVO exportAdminOrderListQueryVO = listQueryVOS.get(i);
                                                exportAdminOrderListQueryVO.setCommission(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setChangePriceDiscount(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setEstimateCommission(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setMemberDiscount(new BigDecimal("0.00"));
                                                //  exportAdminOrderListQueryVO.setPurchaseFeeMoney(new BigDecimal("0.00"));
                                                // exportAdminOrderListQueryVO.setPurchaseFeeMoneyScalePrice(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setRefundAmount(new BigDecimal("0.00"));
                                                //  exportAdminOrderListQueryVO.setScaleBackPrice(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setTheAmountActuallyPaid(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setTotalCommodityPrice(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setUnitPrice(new BigDecimal("0.00"));
                                                exportAdminOrderListQueryVO.setWholesaleDiscount(new BigDecimal("0.00"));
                                            }
                                        }
                                        exList.addAll(listQueryVOS);
                                    }
                                    a=a+1;
                                }
                            }else {
                                for (Date date : collect1.keySet()) {
                                    List<ExportSellerOrderListQueryVO> listQueryVOS = collect1.get(date);
                                    exList.addAll(listQueryVOS);
                                }
                            }
                        }
                    }
                }
                return this.getSellerQuery(list);
            }
            List<ExportSellerOrderListVO> result = new ArrayList<>();
            String[] idArray = ids.split(",");
            for (String id : idArray) {
                // 根据id查询
                List<ExportSellerOrderListQueryVO> list = baseMapper.queryExportSellerOrderList(shopId, Long.valueOf(id), 10,purchaseOrderType);
                List<ExportSellerOrderListQueryVO>  exList= new ArrayList<>();
                if (CustomizeUtil.listIsNotNull(list)){
                    boolean flag=false;
                    for (ExportSellerOrderListQueryVO exportAdminOrderListQueryVO : list) {
                        if (exportAdminOrderListQueryVO.getDeliveryTime()==null){
                            flag=true;
                        }
                    }
                    if (flag){
                        List<ExportSellerOrderListVO> query =  this.getSellerQuery(list);
                        result.addAll(query);
                    }else {
                        Map<Date, List<ExportSellerOrderListQueryVO>> collect = list.stream().collect(Collectors.groupingBy(ExportSellerOrderListQueryVO::getDeliveryTime));
                        if (collect.size()>1){
                            int a=0;
                            for (Date date : collect.keySet()) {
                                if (a==0){
                                    List<ExportSellerOrderListQueryVO> listQueryVOS = collect.get(date);
                                    exList.addAll(listQueryVOS);
                                }else {
                                    List<ExportSellerOrderListQueryVO> listQueryVOS = collect.get(date);
                                    if (CustomizeUtil.listIsNotNull(listQueryVOS)){
                                        for (int i = 0; i < listQueryVOS.size(); i++) {
                                            ExportSellerOrderListQueryVO exportAdminOrderListQueryVO = listQueryVOS.get(i);
                                            exportAdminOrderListQueryVO.setCommission(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setChangePriceDiscount(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setEstimateCommission(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setMemberDiscount(new BigDecimal("0.00"));
                                           // exportAdminOrderListQueryVO.setPurchaseFeeMoney(new BigDecimal("0.00"));
                                         //   exportAdminOrderListQueryVO.setPurchaseFeeMoneyScalePrice(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setRefundAmount(new BigDecimal("0.00"));
                                          //  exportAdminOrderListQueryVO.setScaleBackPrice(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setTheAmountActuallyPaid(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setTotalCommodityPrice(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setUnitPrice(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setWholesaleDiscount(new BigDecimal("0.00"));
                                        }
                                    }
                                    exList.addAll(listQueryVOS);
                                }
                                a=a+1;
                            }
                            List<ExportSellerOrderListVO> query = this.getSellerQuery(exList);
                            result.addAll(query);

                        }else {
                            for (Date date : collect.keySet()) {
                                List<ExportSellerOrderListQueryVO> listQueryVOS = collect.get(date);
                                List<ExportSellerOrderListVO> query = this.getSellerQuery(listQueryVOS);
                                result.addAll(query);
                            }
                        }
                    }
                }
//                List<ExportSellerOrderListVO> query = (list);
//                result.addAll(query);
            }
            return result;
        } catch (Exception e) {
            log.error("订单导出报错信息:{}", e.getMessage());
            e.printStackTrace();
        }
        return this.getSellerQuery(null);
    }

    @Override
    public List<ExportBuyerOrderListVO> queryBuyerOrderList(Long shopId, String ids, Integer status,Integer purchaseOrderType) {
        try {
            // 状态为10查询全部，否则根据订单状态查询
            if ("0".equals(ids)) {
                if (status.equals(10)) {
                    List<ExportAdminOrderListQueryVO> queryList = baseMapper.queryExportAdminOrderList(shopId, null, 10,purchaseOrderType);
                    return this.getBuyerOrder(queryList);
                }
                // 根据订单状态查询
                List<ExportAdminOrderListQueryVO> list = baseMapper.queryExportAdminOrderList(shopId, null, status,purchaseOrderType);
                return this.getBuyerOrder(list);
            }
            List<ExportBuyerOrderListVO> result = new ArrayList<>();
            String[] idArray = ids.split(",");
            for (String id : idArray) {
                // 根据id查询
                List<ExportAdminOrderListQueryVO> list = baseMapper.queryExportAdminOrderList(shopId, Long.valueOf(id), 10,purchaseOrderType);
                List<ExportAdminOrderListQueryVO>  exList= new ArrayList<>();
                if (CustomizeUtil.listIsNotNull(list)){
                    boolean flag=false;
                    for (ExportAdminOrderListQueryVO exportAdminOrderListQueryVO : list) {
                        if (exportAdminOrderListQueryVO.getDeliveryTime()==null){
                            flag=true;
                        }
                    }
                    if (flag){
                        List<ExportBuyerOrderListVO> query = this.getBuyerOrder(list);
                        result.addAll(query);
                    }else {
                        Map<Date, List<ExportAdminOrderListQueryVO>> collect = list.stream().collect(Collectors.groupingBy(ExportAdminOrderListQueryVO::getDeliveryTime));
                        if (collect.size()>1){
                            int a=0;
                            for (Date date : collect.keySet()) {
                                if (a==0){
                                    List<ExportAdminOrderListQueryVO> listQueryVOS = collect.get(date);
                                    exList.addAll(listQueryVOS);
                                }else {
                                    List<ExportAdminOrderListQueryVO> listQueryVOS = collect.get(date);
                                    if (CustomizeUtil.listIsNotNull(listQueryVOS)){
                                        for (int i = 0; i < listQueryVOS.size(); i++) {
                                            ExportAdminOrderListQueryVO exportAdminOrderListQueryVO = listQueryVOS.get(i);
                                            exportAdminOrderListQueryVO.setCommission(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setChangePriceDiscount(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setEstimateCommission(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setMemberDiscount(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setPurchaseFeeMoney(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setPurchaseFeeMoneyScalePrice(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setRefundAmount(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setScaleBackPrice(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setTheAmountActuallyPaid(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setTotalCommodityPrice(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setUnitPrice(new BigDecimal("0.00"));
                                            exportAdminOrderListQueryVO.setWholesaleDiscount(new BigDecimal("0.00"));
                                        }
                                    }
                                    exList.addAll(listQueryVOS);
                                }
                                a=a+1;
                            }
                            List<ExportBuyerOrderListVO> query = this.getBuyerOrder(exList);
                            result.addAll(query);

                        }else {
                            for (Date date : collect.keySet()) {
                                List<ExportAdminOrderListQueryVO> listQueryVOS = collect.get(date);
                                List<ExportBuyerOrderListVO> query = this.getBuyerOrder(listQueryVOS);
                                result.addAll(query);
                            }
                        }
                    }
                }
               // List<ExportBuyerOrderListVO> query = this.getBuyerOrder(list);
               // result.addAll(query);
            }
            return result;
        } catch (Exception e) {
            log.error("订单导出报错信息:{}", e.getMessage());
            e.printStackTrace();
        }
        return this.getBuyerOrder(null);
    }

    @Override
    public boolean checkOrderIsInquiry(String orderIds) {
        String[] orderIdList = orderIds.split(",");
        for (String id : orderIdList) {
            Long orderId = Long.parseLong(id);
            // 查询订单
            OrderInfoDTO orderDto = this.selectById(orderId);
            // 订单类型:0普通,1询价
            Integer type = orderDto.getType();
            log.info("订单类型:{}", type);
            // 普通订单跳过,询价订单检查是否有未改价的
            if (type.equals(1)) {
                // 询价订单查询订单商品
                Wrapper<OrderCommodityRelationDTO> wrapper = new EntityWrapper<>();
                wrapper.eq("order_id", orderId);
                List<OrderCommodityRelationDTO> orderCommodityRelationList = orderCommodityRelationService.selectList(wrapper);
                for (OrderCommodityRelationDTO commodityRelationDTO : orderCommodityRelationList) {
                    if(commodityRelationDTO.getPurchaseCommodityType() == BargainStateEnum.PURCHASE_COMMODITY_OK.getCode()){//如果询盘商品则跳过
                        continue;
                    }
                    // 先判断是否是询价商品
                    CommodityInfoDTO commodityInfoDTO = commodityInfoService.selectById(commodityRelationDTO.getCommodityId());
                    // 0普通,1询价
                    Integer isInquiry = commodityInfoDTO.getIsInquiry();
                    if (null != isInquiry &&  isInquiry.equals(1)) {
                        // 如果订单商品中存在尚未改价的返回失败
                        if (commodityRelationDTO.getIsChangePrice().equals(0)) {
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

    @Override
    public List<String> printingElectronicReceipt(String orderId, String shopId, String date) {
        return payOrderService.printingElectronicReceipt(orderId, shopId, date);
    }

    @Override
    public PayBatchPrintVO printingBatchElectronicReceipt(List<PayBatchPrintBO> list) {
        return payOrderService.printingBatchElectronicReceipt(list);
    }

    @Transactional
    @Override
    public Result saveAgreeBillPay(Long id) {
        //查看是否是有票据支付
        Wrapper  wrapper = new EntityWrapper();
        wrapper.eq("order_id", id);
        wrapper.eq("pay_state", 1);
        wrapper.eq("pay_type", 2);
        OrderPayRelationDTO relationDTO = orderPayRelationService.selectOne(wrapper);
        if(relationDTO == null){
            return new Result(CodeEnum.FAIL_200038);
        }

        wrapper = new EntityWrapper();
        wrapper.eq("order_periods_id", relationDTO.getId());
        wrapper.eq("status", 0);
        wrapper.eq("pay_type", 2);
        PayOrderLogDTO logDTO = payOrderLogService.selectOne(wrapper);
        if(logDTO == null){
            throw new ServiceException(CodeEnum.FAIL_100011);
        }

        payOrderLogService.savePayOrderLogDTOStatus(logDTO.getId(), null, 2, 0);

        PayOrderDTO orderDTO = new PayOrderDTO();
        orderDTO.setStatus(2);
        orderDTO.setType(2);
        payService.saveOrderPaySuccess(orderDTO, logDTO);
        return new Result();
//        OrderInfoDTO infoDTO = orderInfoMapper.selectById(id);
//        OrderStatusDTO statusDTO = orderStatusService.getByOrderId(id);
//
//        if(relationDTO.getPeriods() == 1 && infoDTO.getPayType() == 1){
//            OrderStatusDTO newDTO = new OrderStatusDTO();
//            newDTO.setGoodsProductionState(1);
//            wrapper = new EntityWrapper();
//            wrapper.eq("order_id", id);
//            if(!orderStatusService.update(newDTO, wrapper)){
//                throw new ServiceException(CodeEnum.FAIL_100011);
//            }
//        }
//
//        OrderPayRelationDTO newRelationDTO = new OrderPayRelationDTO();
//        newRelationDTO.setPayState(2);
//        newRelationDTO.setPaySuccessTime(new Date());
//        wrapper = new EntityWrapper();
//        wrapper.eq("id", relationDTO.getId());
//        wrapper.eq("order_id", id);
//        wrapper.eq("pay_state", 1);
//        wrapper.eq("pay_type", 2);
//        boolean flag = orderPayRelationService.update(newRelationDTO, wrapper);
//        if(!flag){
//            throw new ServiceException(CodeEnum.FAIL_100011);
//        }
//
//        OrderPaymentTypeDTO typeDTO = orderPaymentTypeService.getOrderPaymentByOrderIdAndType(id, 2);
//        if(typeDTO != null){
//            OrderPaymentScaleDTO newScaleDTO = new OrderPaymentScaleDTO();
//            newScaleDTO.setPaymentStatus(2);
//            newScaleDTO.setPaymentSuccessTime(new Date());
//            wrapper = new EntityWrapper();
//            wrapper.eq("order_id", id);
//            wrapper.eq("pay_relation_id", relationDTO.getId());
//            wrapper.eq("payment_status", 1);
//            //wrapper.eq("payment_type", 2);
//            flag = orderPaymentScaleService.update(newScaleDTO, wrapper);
//            if(!flag){
//                throw new ServiceException(CodeEnum.FAIL_100011);
//            }
//        } else {
//            //处理分期订单
//            if(relationDTO.getPeriods() == 2){//分期订单
//                OrderStatusDTO newDTO = new OrderStatusDTO();
//                newDTO.setGoodsProductionState(1);
//                wrapper = new EntityWrapper();
//                wrapper.eq("order_id", id);
//                if(!orderStatusService.update(newDTO, wrapper)){
//                    throw new ServiceException(CodeEnum.FAIL_100011);
//                }
//
//                //更改订单发货倒计时
//                List<Integer> sendList = new ArrayList<Integer>();
//                //处理多个商品中获取发货时间为最少的
//                for(OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationDTOList){
//                    sendList.add(orderCommodityRelationDTO.getSendDays());
//                }
//                Integer sendDaysNum = Collections.min(sendList);
//                //更新倒计时
//                OrderExpirationDateDTO orderExpirationDateDTO = orderExpirationDateService.getByOrderId(orderId);
//                //SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.WAIT_DELIVER_GOODS);//卖家签订合同后倒计时
//
//                Date expireTime = DateUtils.addDay(currentDateTime, sendDaysNum);//过期时间
//
//                OrderExpirationDateDTO newExpirationDateDTO = new OrderExpirationDateDTO();
//                newExpirationDateDTO.setId(orderExpirationDateDTO.getId());
//                newExpirationDateDTO.setExpirationTime(expireTime);
//                newExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode());
//                wrapper = new EntityWrapper();
//                wrapper.eq("id", orderExpirationDateDTO.getId());
//                wrapper.eq("status", orderExpirationDateDTO.getStatus());
//
//                String tiem = DateUtils.dateToStr(expireTime);
//                log.info("orderid-------"+orderId+"--------待发货倒计时3----------"+tiem+"---------天数-----"+sendDaysNum);
//
//                flag = orderExpirationDateService.update(newExpirationDateDTO, wrapper);//更新倒计时
//                if(!flag){
//                    throw new ServiceException(CodeEnum.FAIL_100011);
//                }
//                // 待发货截止时间
//                flag =  orderDeadlineRecordService.insert(orderId, 5, expireTime);
//                if(!flag){
//                    throw new ServiceException(CodeEnum.FAIL_100011);
//                }
//
//            }
//
//            if(orderInfoDTO.getPayType() == 1){
//                //修改备货时间
//                if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGN.getCode()) {
//                    OrderExpirationDateDTO orderExpirationDateDTO = orderExpirationDateService.getByOrderId(orderId);
//                    //处理备货过期倒计时
//                    Date stockExpireTime = DateUtils.addDay(currentDateTime, orderCommodityRelationDTOList.get(0).getStockDays());//过期时间
//                    orderExpirationDateDTO.setExpirationTime(stockExpireTime);
//                    orderExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_PAY.getCode());
//                    flag = orderExpirationDateService.updateByOrderId(orderExpirationDateDTO);//更新过期时间
//                    if(!flag){
//                        throw new ServiceException(CodeEnum.FAIL_100011);
//                    }
//                    // 记录备货截止时间
//                    flag = orderDeadlineRecordService.insert(orderId, 9, stockExpireTime);
//                    if(!flag){
//                        throw new ServiceException(CodeEnum.FAIL_100011);
//                    }
//                    log.info("orderid-------" + orderId + "--------备货倒计时5----------");
//                }
//            }
//        }
//
//
//        PayOrderLogDTO newLogDTO = new PayOrderLogDTO();
//        newLogDTO.setStatus(2);
//        wrapper = new EntityWrapper();
//        wrapper.eq("order_periods_id", relationDTO.getId());
//        wrapper.eq("status", 0);
//        wrapper.eq("pay_type", 2);
//        flag = payOrderLogService.update(newLogDTO, wrapper);
//        if(!flag){
//            throw new ServiceException(CodeEnum.FAIL_100011);
//        }
//
//        //修改订单支付完成状态
//        orderPaymentTypeService.updatePayStatus(id, relationDTO.getId());
//
//        //支付佣金
//        boolean payCommissionMoney = false;
//        if(relationDTO.getPeriods() == 1){
//            payCommissionMoney = true;
//        } else if(relationDTO.getPeriods() == 2){
//            OrderStatusDTO statusDTO = orderStatusService.getByOrderId(id);
//            if(infoDTO.getPayType() == 1 && statusDTO.getCommissionMoneyPayStatus() != 2){ //预售
//                payCommissionMoney = true;
//            }
//        }
//        if(payCommissionMoney){
//            PayOrderSaveBO payOrderSaveBO = new PayOrderSaveBO();
//            payOrderSaveBO.setType(1);
//            payOrderSaveBO.setIds(id.toString());
//            payOrderSaveBO.setPayType(0);
//            Result result = payService.savePay(payOrderSaveBO, false);
//            if(!result.success()){
//                throw new ServiceException(result.getCode(), result.getMsg());
//            }
//        }
//
//        return new Result();
    }

    @Transactional
    @Override
    public Result saveNoAgreeBillPay(Long id) {
        Wrapper  wrapper = new EntityWrapper();
        wrapper.eq("order_id", id);
        wrapper.eq("pay_state", 1);
        wrapper.eq("pay_type", 2);
        OrderPayRelationDTO relationDTO = orderPayRelationService.selectOne(wrapper);
        if(relationDTO == null){
            return new Result(CodeEnum.FAIL_200038);
        }

        OrderPayRelationDTO newRelationDTO = new OrderPayRelationDTO();
        newRelationDTO.setPayState(3);
        wrapper = new EntityWrapper();
        wrapper.eq("order_id", id);
        wrapper.eq("pay_state", 1);
        wrapper.eq("pay_type", 2);
        boolean flag = orderPayRelationService.update(newRelationDTO, wrapper);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_100011);
        }

        OrderPaymentTypeDTO typeDTO = orderPaymentTypeService.getOrderPaymentByOrderIdAndType(id, 1,2);
        if(typeDTO != null){
            OrderPaymentScaleDTO newScaleDTO = new OrderPaymentScaleDTO();
            newScaleDTO.setPaymentStatus(3);
            wrapper = new EntityWrapper();
            wrapper.eq("order_id", id);
            wrapper.eq("pay_relation_id", relationDTO.getId());
            wrapper.eq("payment_status", 1);
            flag = orderPaymentScaleService.update(newScaleDTO, wrapper);
            if(!flag){
                throw new ServiceException(CodeEnum.FAIL_100011);
            }
        }

        PayOrderLogDTO newLogDTO = new PayOrderLogDTO();
        newLogDTO.setStatus(3);
        wrapper = new EntityWrapper();
        wrapper.eq("order_periods_id", relationDTO.getId());
        wrapper.eq("status", 0);
        wrapper.eq("pay_type", 2);
        flag = payOrderLogService.update(newLogDTO, wrapper);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_100011);
        }
        OrderInfoDTO infoDTO = orderInfoMapper.selectById(id);
        asyncOrderService.sendOrderSms(infoDTO.getBuyShopId(), String.format(SURE_PAY_BILL, infoDTO.getOrderNo()));
        return new Result();
    }

    @Override
    public Result getOrderCategory() {
        EntityWrapper<OrderCommodityRelationDTO> wrapper = new EntityWrapper<>();
        List<OrderCommodityRelationDTO> orderCommodityRelationDTOS = orderCommodityRelationService.selectList(wrapper);
        List<OrderCommodityRelationDTO> orderCommodityRelationDTOList = new ArrayList<>();
        if (CustomizeUtil.listIsNotNull(orderCommodityRelationDTOS)){
            for (OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationDTOS) {
                if (orderCommodityRelationDTO.getCommodityCategoryId()==null){
                    orderCommodityRelationDTOList.add(orderCommodityRelationDTO);
                }

            }
        }
       if (CustomizeUtil.listIsNotNull(orderCommodityRelationDTOList)){
           for (OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationDTOList) {
               PurchaseCommodityBargainDTO purchaseCommodityBargainDTO = purchaseCommodityBargainService.selectById(orderCommodityRelationDTO.getPurchaseCommodityBargainId());
              if (purchaseCommodityBargainDTO!=null){
                  CommodityInfoDTO commodityInfoDTO = commodityInfoService.selectById(purchaseCommodityBargainDTO.getCommodityId());
                  if (commodityInfoDTO!=null)
                  orderCommodityRelationDTO.setCommodityCategoryId(commodityInfoDTO.getCategoryId());
                  boolean b = orderCommodityRelationService.updateById(orderCommodityRelationDTO);
                  log.info("同步修改数据"+b);
              }
           }
       }

        return new Result();
    }

    @Override
    public Page<OrderInfoShipVO> queryOrderShip(OrderAdminListBO bo) {
        Page<OrderInfoShipVO> page = new Page<>(bo.getPageNo(),bo.getPageSize());
        List<OrderInfoShipVO> list=orderInfoMapper.queryOrderShip(page,bo);
        page.setRecords(list);
        return page;
    }

    /**
     * @return : java.util.List<com.ztgf.order.models.vo.ExportBuyerOrderListVO>
     * @Author :chenyu.wang
     * @Description : 买家订单导出封装
     * @Date : 2021.03.02 11:11
     * @Param : [list]
     **/
    private List<ExportBuyerOrderListVO> getBuyerOrder(List<ExportAdminOrderListQueryVO> list) {
        // 结果集合
        List<ExportBuyerOrderListVO> result = new ArrayList<>();
        if (CustomizeUtil.listIsNull(list)) {
            BigDecimal price = new BigDecimal("0.00");
            ExportBuyerOrderListVO vo = new ExportBuyerOrderListVO();
            vo.setUnitPrice(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setTotalCommodityPrice(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setChangePriceDiscount(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setWholesaleDiscount(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setMemberDiscount(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setTheAmountActuallyPaid(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setRefundAmount(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setScaleBackPrice(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setPurchaseFeeMoneyScalePrice(price.setScale(2, BigDecimal.ROUND_UP));
            result.add(vo);
            return result;
        }
        // 不为空
        for (ExportAdminOrderListQueryVO queryVO : list) {
            ExportBuyerOrderListVO exportAdminOrderListVO = new ExportBuyerOrderListVO();
            exportAdminOrderListVO.setOrderNumber(queryVO.getOrderNumber());
            exportAdminOrderListVO.setOrderStatus(this.getOrderState(queryVO.getOrderStatus()));
            exportAdminOrderListVO.setProductName(queryVO.getProductName());
            exportAdminOrderListVO.setBuyerUsername(queryVO.getBuyerUsername());
            exportAdminOrderListVO.setSellerName(queryVO.getSellerName());
            exportAdminOrderListVO.setConsignee(queryVO.getConsignee());
            exportAdminOrderListVO.setConsigneePhone(queryVO.getConsigneePhone());
            exportAdminOrderListVO.setShippingAddress(queryVO.getShippingAddress());
            exportAdminOrderListVO.setUnitPrice(queryVO.getUnitPrice().setScale(2, BigDecimal.ROUND_UP));
            exportAdminOrderListVO.setAmount(queryVO.getAmount());
            exportAdminOrderListVO.setTotalCommodityPrice(queryVO.getTotalCommodityPrice().setScale(2, BigDecimal.ROUND_UP));
            exportAdminOrderListVO.setChangePriceDiscount(queryVO.getChangePriceDiscount().setScale(2, BigDecimal.ROUND_UP));
            exportAdminOrderListVO.setWholesaleDiscount(queryVO.getWholesaleDiscount().setScale(2, BigDecimal.ROUND_UP));
            exportAdminOrderListVO.setMemberDiscount(queryVO.getMemberDiscount().setScale(2, BigDecimal.ROUND_UP));
            exportAdminOrderListVO.setTheAmountActuallyPaid(queryVO.getTheAmountActuallyPaid().setScale(2, BigDecimal.ROUND_UP));
            exportAdminOrderListVO.setOrderTime(DateUtils.dateToStr(queryVO.getOrderTime(), DateUtils.DATE_FORMAT_DATETIME));
            exportAdminOrderListVO.setScaleBackPrice(queryVO.getScaleBackPrice().setScale(2, BigDecimal.ROUND_UP));
            exportAdminOrderListVO.setPurchaseFeeMoneyScalePrice(queryVO.getPurchaseFeeMoneyScalePrice().setScale(2, BigDecimal.ROUND_UP));
            if (queryVO.getPaymentTime() != null) {
                exportAdminOrderListVO.setPaymentTime(DateUtils.dateToStr(queryVO.getPaymentTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getSubmissionTime() != null) {
                exportAdminOrderListVO.setSubmissionTime(DateUtils.dateToStr(queryVO.getSubmissionTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getFirstPaymentTime() != null) {
                exportAdminOrderListVO.setFirstPaymentTime(DateUtils.dateToStr(queryVO.getFirstPaymentTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getFinalPaymentTime() != null) {
                exportAdminOrderListVO.setFinalPaymentTime(DateUtils.dateToStr(queryVO.getFinalPaymentTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getDeliveryTime() != null) {
                exportAdminOrderListVO.setDeliveryTime(DateUtils.dateToStr(queryVO.getDeliveryTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getDeliveryMethod() != null) {
                if (queryVO.getDeliveryMethod().equals(0)) {
                    exportAdminOrderListVO.setDeliveryMethod("物流配送");
                } else {
                    exportAdminOrderListVO.setDeliveryMethod("自行配送");
                }
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getLogisticsCompany())) {
                exportAdminOrderListVO.setLogisticsCompany(queryVO.getLogisticsCompany());
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getShipmentNumber())) {
                exportAdminOrderListVO.setShipmentNumber(queryVO.getShipmentNumber());
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getLogisticsContact())) {
                exportAdminOrderListVO.setLogisticsContact(queryVO.getLogisticsContact());
            }
            if (queryVO.getInvoiceType() != null) {
                if (queryVO.getInvoiceType().equals(0)) {
                    exportAdminOrderListVO.setInvoiceType("增值税普通发票");
                } else {
                    exportAdminOrderListVO.setInvoiceType("增值税专用发票");
                }
            }
            if (queryVO.getInvoiceState() != null) {
                if (queryVO.getInvoiceState().equals(0)) {
                    exportAdminOrderListVO.setInvoiceState("未开票");
                } else if(queryVO.getInvoiceState().equals(1)){
                    exportAdminOrderListVO.setInvoiceState("申请中");
                } else {
                    exportAdminOrderListVO.setInvoiceState("已开票");
                }
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getBillingInformation())) {
                exportAdminOrderListVO.setBillingInformation(queryVO.getBillingInformation());
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getInvoiceDeliveryAddress())) {
                exportAdminOrderListVO.setInvoiceDeliveryAddress(queryVO.getInvoiceDeliveryAddress());
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getRemarksInformation())) {
                exportAdminOrderListVO.setRemarksInformation(queryVO.getRemarksInformation());
            }
            exportAdminOrderListVO.setRefundAmount(queryVO.getRefundAmount().setScale(2, BigDecimal.ROUND_UP));
            result.add(exportAdminOrderListVO);
        }
        return result;
    }

    /**
     * @return : java.util.List<com.ztgf.order.models.vo.ExportAdminOrderListVO>
     * @Author :chenyu.wang
     * @Description : 处理导出结果
     * @Date : 2021.02.25 17:22
     * @Param : [list]
     **/
    private List<ExportAdminOrderListVO> getQuery(List<ExportAdminOrderListQueryVO> list) {
        // 结果集合
        List<ExportAdminOrderListVO> result = new ArrayList<>();
        if (CustomizeUtil.listIsNull(list)) {
            BigDecimal price = new BigDecimal("0.00");
            ExportAdminOrderListVO vo = new ExportAdminOrderListVO();
            vo.setUnitPrice(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setTotalCommodityPrice(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setChangePriceDiscount(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setWholesaleDiscount(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setMemberDiscount(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setTheAmountActuallyPaid(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setCommission(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setEstimateCommission(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setRefundAmount(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setPurchaseFeeMoney(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setPurchaseFeeMoneyScalePrice(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setScaleBackPrice(price.setScale(2, BigDecimal.ROUND_UP));
            result.add(vo);
            return result;
        }
        // 不为空
        for (ExportAdminOrderListQueryVO queryVO : list) {
            ExportAdminOrderListVO exportAdminOrderListVO = new ExportAdminOrderListVO();
            exportAdminOrderListVO.setPurchaseInfoId(queryVO.getPurchaseInfoId());
            exportAdminOrderListVO.setPurchaseFeeMoney(queryVO.getPurchaseFeeMoney());
            exportAdminOrderListVO.setPurchaseFeeMoneyScalePrice(queryVO.getPurchaseFeeMoneyScalePrice());
            exportAdminOrderListVO.setOrderNumber(queryVO.getOrderNumber());
            exportAdminOrderListVO.setOrderStatus(this.getOrderState(queryVO.getOrderStatus()));
            exportAdminOrderListVO.setProductName(queryVO.getProductName());
            exportAdminOrderListVO.setBuyerUsername(queryVO.getBuyerUsername());
            exportAdminOrderListVO.setSellerName(queryVO.getSellerName());
            exportAdminOrderListVO.setConsignee(queryVO.getConsignee());
            exportAdminOrderListVO.setConsigneePhone(queryVO.getConsigneePhone());
            exportAdminOrderListVO.setShippingAddress(queryVO.getShippingAddress());
            exportAdminOrderListVO.setUnitPrice(queryVO.getUnitPrice().setScale(2, BigDecimal.ROUND_UP));
            exportAdminOrderListVO.setAmount(queryVO.getAmount());
            exportAdminOrderListVO.setTotalCommodityPrice(queryVO.getTotalCommodityPrice().setScale(2, BigDecimal.ROUND_UP));
            exportAdminOrderListVO.setChangePriceDiscount(queryVO.getChangePriceDiscount().setScale(2, BigDecimal.ROUND_UP));
            exportAdminOrderListVO.setWholesaleDiscount(queryVO.getWholesaleDiscount().setScale(2, BigDecimal.ROUND_UP));
            exportAdminOrderListVO.setMemberDiscount(queryVO.getMemberDiscount().setScale(2, BigDecimal.ROUND_UP));
            exportAdminOrderListVO.setTheAmountActuallyPaid(queryVO.getTheAmountActuallyPaid().setScale(2, BigDecimal.ROUND_UP));
            exportAdminOrderListVO.setOrderTime(DateUtils.dateToStr(queryVO.getOrderTime(), DateUtils.DATE_FORMAT_DATETIME));
            exportAdminOrderListVO.setScaleBackPrice(queryVO.getScaleBackPrice().setScale(2, BigDecimal.ROUND_UP));
            if (queryVO.getPaymentTime() != null) {
                exportAdminOrderListVO.setPaymentTime(DateUtils.dateToStr(queryVO.getPaymentTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getCommissionPayTime() != null) {
                exportAdminOrderListVO.setCommissionPayTime(DateUtils.dateToStr(queryVO.getCommissionPayTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getCommissionRefundTime() != null) {
                exportAdminOrderListVO.setCommissionRefundTime(DateUtils.dateToStr(queryVO.getCommissionRefundTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getSubmissionTime() != null) {
                exportAdminOrderListVO.setSubmissionTime(DateUtils.dateToStr(queryVO.getSubmissionTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getFirstPaymentTime() != null) {
                exportAdminOrderListVO.setFirstPaymentTime(DateUtils.dateToStr(queryVO.getFirstPaymentTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getFinalPaymentTime() != null) {
                exportAdminOrderListVO.setFinalPaymentTime(DateUtils.dateToStr(queryVO.getFinalPaymentTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getDeliveryTime() != null) {
                exportAdminOrderListVO.setDeliveryTime(DateUtils.dateToStr(queryVO.getDeliveryTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getDeliveryMethod() != null) {
                if (queryVO.getDeliveryMethod().equals(0)) {
                    exportAdminOrderListVO.setDeliveryMethod("物流配送");
                } else {
                    exportAdminOrderListVO.setDeliveryMethod("自行配送");
                }
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getLogisticsCompany())) {
                exportAdminOrderListVO.setLogisticsCompany(queryVO.getLogisticsCompany());
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getShipmentNumber())) {
                exportAdminOrderListVO.setShipmentNumber(queryVO.getShipmentNumber());
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getLogisticsContact())) {
                exportAdminOrderListVO.setLogisticsContact(queryVO.getLogisticsContact());
            }
            if (queryVO.getInvoiceType() != null) {
                if (queryVO.getInvoiceType().equals(0)) {
                    exportAdminOrderListVO.setInvoiceType("增值税普通发票");
                } else {
                    exportAdminOrderListVO.setInvoiceType("增值税专用发票");
                }
            }
            if (queryVO.getInvoiceState() != null) {
                if (queryVO.getInvoiceState().equals(0)) {
                    exportAdminOrderListVO.setInvoiceState("未开票");
                } else if(queryVO.getInvoiceState().equals(1)){
                    exportAdminOrderListVO.setInvoiceState("申请中");
                } else {
                    exportAdminOrderListVO.setInvoiceState("已开票");
                }
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getBillingInformation())) {
                exportAdminOrderListVO.setBillingInformation(queryVO.getBillingInformation());
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getInvoiceDeliveryAddress())) {
                exportAdminOrderListVO.setInvoiceDeliveryAddress(queryVO.getInvoiceDeliveryAddress());
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getRemarksInformation())) {
                exportAdminOrderListVO.setRemarksInformation(queryVO.getRemarksInformation());
            }
            if (queryVO.getOrderNumber()!=null && queryVO.getOrderNumber()!=""){
                OrderStatVo orderStatVo=orderInfoMapper.getStatusByOrderNum(queryVO.getOrderNumber());
                if (orderStatVo!=null) {
                    //实际佣金
                    if (orderStatVo.getSellPayType() != null && orderStatVo.getOrderState() != null) {
                        if (orderStatVo.getSellPayType() == 0 && orderStatVo.getOrderState() != 5) {
                            exportAdminOrderListVO.setCommission(new BigDecimal(0.00));
                        }
                        if (orderStatVo.getSellPayType() == 0 && orderStatVo.getOrderState() == 5) {
                            exportAdminOrderListVO.setCommission(queryVO.getCommission().setScale(2, BigDecimal.ROUND_UP));
                        }
                    }
                    if (orderStatVo.getSellPayType()!=null && orderStatVo.getPayState()!=null){
                        if (orderStatVo.getSellPayType()==1&&orderStatVo.getPayState()!=2){
                            exportAdminOrderListVO.setCommission(new BigDecimal(0.00));
                        }
                        if (orderStatVo.getSellPayType()==1&&orderStatVo.getPayState()==2){
                            exportAdminOrderListVO.setCommission(queryVO.getCommission().setScale(2, BigDecimal.ROUND_UP));
                        }
                    }
                    //预算佣金
                    // exportSellerOrderListVO.setCommission(queryVO.getCommission().setScale(2, BigDecimal.ROUND_UP));
                    if (orderStatVo.getPayState()!=null){
                        if (orderStatVo.getPayState()!=null){
                            if (orderStatVo.getPayState()!=2){
                                exportAdminOrderListVO.setEstimateCommission(new BigDecimal(0.00));

                            }
                            if (orderStatVo.getPayState()==2){
                                exportAdminOrderListVO.setEstimateCommission(queryVO.getEstimateCommission().setScale(2, BigDecimal.ROUND_UP));

                            }
                        }
                    }
                }
            }
          /*  exportAdminOrderListVO.setCommission(queryVO.getCommission().setScale(2, BigDecimal.ROUND_UP));
            exportAdminOrderListVO.setEstimateCommission(queryVO.getEstimateCommission().setScale(2, BigDecimal.ROUND_UP));*/
            exportAdminOrderListVO.setRefundAmount(queryVO.getRefundAmount().setScale(2, BigDecimal.ROUND_UP));
            for(ExportAdminOrderListVO exportAdminOrderListVO1 : result){
                if(exportAdminOrderListVO1.getOrderNumber().equals(exportAdminOrderListVO.getOrderNumber())){//如果有重复的就将该条重复数据预计技术服务费，实际技术服务器都设置为0.00
                    exportAdminOrderListVO.setCommission(new BigDecimal(0.00));
                    exportAdminOrderListVO.setEstimateCommission(new BigDecimal(0.00));
                }
            }
            if(result.contains(exportAdminOrderListVO)){
                exportAdminOrderListVO.setPurchaseFeeMoney(new BigDecimal(0.00));
            }
            result.add(exportAdminOrderListVO);
        }
        return result;
    }

    /**
     * @return : java.util.List<com.ztgf.order.models.vo.ExportAdminOrderListVO>
     * @Author :chenyu.wang
     * @Description : 处理导出结果
     * @Date : 2021.02.25 17:22
     * @Param : [list]
     **/
    private List<ExportSellerOrderListVO> getSellerQuery(List<ExportSellerOrderListQueryVO> list) {
        // 结果集合
        List<ExportSellerOrderListVO> result = new ArrayList<>();
        if (CustomizeUtil.listIsNull(list)) {
            BigDecimal price = new BigDecimal("0.00");
            ExportSellerOrderListVO vo = new ExportSellerOrderListVO();
            vo.setUnitPrice(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setTotalCommodityPrice(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setChangePriceDiscount(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setWholesaleDiscount(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setMemberDiscount(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setTheAmountActuallyPaid(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setCommission(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setEstimateCommission(price.setScale(2, BigDecimal.ROUND_UP));
            vo.setRefundAmount(price.setScale(2, BigDecimal.ROUND_UP));
            result.add(vo);
            return result;
        }
        // 不为空
        for (ExportSellerOrderListQueryVO queryVO : list) {
            ExportSellerOrderListVO exportSellerOrderListVO = new ExportSellerOrderListVO();
            exportSellerOrderListVO.setOrderNumber(queryVO.getOrderNumber());
            exportSellerOrderListVO.setOrderStatus(this.getOrderState(queryVO.getOrderStatus()));
            exportSellerOrderListVO.setProductName(queryVO.getProductName());
            exportSellerOrderListVO.setBuyerUsername(queryVO.getBuyerUsername());
            exportSellerOrderListVO.setSellerName(queryVO.getSellerName());
            exportSellerOrderListVO.setConsignee(queryVO.getConsignee());
            exportSellerOrderListVO.setConsigneePhone(queryVO.getConsigneePhone());
            exportSellerOrderListVO.setShippingAddress(queryVO.getShippingAddress());
            exportSellerOrderListVO.setUnitPrice(queryVO.getUnitPrice().setScale(2, BigDecimal.ROUND_UP));
            exportSellerOrderListVO.setAmount(queryVO.getAmount());
            exportSellerOrderListVO.setTotalCommodityPrice(queryVO.getTotalCommodityPrice().setScale(2, BigDecimal.ROUND_UP));
            exportSellerOrderListVO.setChangePriceDiscount(queryVO.getChangePriceDiscount().setScale(2, BigDecimal.ROUND_UP));
            exportSellerOrderListVO.setWholesaleDiscount(queryVO.getWholesaleDiscount().setScale(2, BigDecimal.ROUND_UP));
            exportSellerOrderListVO.setMemberDiscount(queryVO.getMemberDiscount().setScale(2, BigDecimal.ROUND_UP));
            exportSellerOrderListVO.setTheAmountActuallyPaid(queryVO.getTheAmountActuallyPaid().setScale(2, BigDecimal.ROUND_UP));
            exportSellerOrderListVO.setOrderTime(DateUtils.dateToStr(queryVO.getOrderTime(), DateUtils.DATE_FORMAT_DATETIME));
            if (queryVO.getPaymentTime() != null) {
                exportSellerOrderListVO.setPaymentTime(DateUtils.dateToStr(queryVO.getPaymentTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getSubmissionTime() != null) {
                exportSellerOrderListVO.setSubmissionTime(DateUtils.dateToStr(queryVO.getSubmissionTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getFirstPaymentTime() != null) {
                exportSellerOrderListVO.setFirstPaymentTime(DateUtils.dateToStr(queryVO.getFirstPaymentTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getFinalPaymentTime() != null) {
                exportSellerOrderListVO.setFinalPaymentTime(DateUtils.dateToStr(queryVO.getFinalPaymentTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getDeliveryTime() != null) {
                exportSellerOrderListVO.setDeliveryTime(DateUtils.dateToStr(queryVO.getDeliveryTime(), DateUtils.DATE_FORMAT_DATETIME));
            }
            if (queryVO.getDeliveryMethod() != null) {
                if (queryVO.getDeliveryMethod().equals(0)) {
                    exportSellerOrderListVO.setDeliveryMethod("物流配送");
                } else {
                    exportSellerOrderListVO.setDeliveryMethod("自行配送");
                }
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getLogisticsCompany())) {
                exportSellerOrderListVO.setLogisticsCompany(queryVO.getLogisticsCompany());
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getShipmentNumber())) {
                exportSellerOrderListVO.setShipmentNumber(queryVO.getShipmentNumber());
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getLogisticsContact())) {
                exportSellerOrderListVO.setLogisticsContact(queryVO.getLogisticsContact());
            }
            if (queryVO.getInvoiceType() != null) {
                if (queryVO.getInvoiceType().equals(0)) {
                    exportSellerOrderListVO.setInvoiceType("增值税普通发票");
                } else {
                    exportSellerOrderListVO.setInvoiceType("增值税专用发票");
                }
            }
            if (queryVO.getInvoiceState() != null) {
                if (queryVO.getInvoiceState().equals(0)) {
                    exportSellerOrderListVO.setInvoiceState("未开票");
                } else if(queryVO.getInvoiceState().equals(1)){
                    exportSellerOrderListVO.setInvoiceState("申请中");
                } else {
                    exportSellerOrderListVO.setInvoiceState("已开票");
                }
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getBillingInformation())) {
                exportSellerOrderListVO.setBillingInformation(queryVO.getBillingInformation());
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getInvoiceDeliveryAddress())) {
                exportSellerOrderListVO.setInvoiceDeliveryAddress(queryVO.getInvoiceDeliveryAddress());
            }
            if (CustomizeUtil.strIsNotNull(queryVO.getRemarksInformation())) {
                exportSellerOrderListVO.setRemarksInformation(queryVO.getRemarksInformation());
            }
            if (queryVO.getOrderNumber()!=null && queryVO.getOrderNumber()!=""){
                OrderStatVo orderStatVo=orderInfoMapper.getStatusByOrderNum(queryVO.getOrderNumber());
                if (orderStatVo!=null) {
                    //实际佣金
                    if (orderStatVo.getSellPayType() != null && orderStatVo.getOrderState() != null) {
                        if (orderStatVo.getSellPayType() == 0 && orderStatVo.getOrderState() != 5) {
                            exportSellerOrderListVO.setCommission(new BigDecimal(0.00));
                        }
                        if (orderStatVo.getSellPayType() == 0 && orderStatVo.getOrderState() == 5) {
                            exportSellerOrderListVO.setCommission(queryVO.getCommission().setScale(2, BigDecimal.ROUND_UP));
                        }
                    }
                    if (orderStatVo.getSellPayType()!=null && orderStatVo.getPayState()!=null){
                        if (orderStatVo.getSellPayType()==1&&orderStatVo.getPayState()!=2){
                            exportSellerOrderListVO.setCommission(new BigDecimal(0.00));
                        }
                        if (orderStatVo.getSellPayType()==1&&orderStatVo.getPayState()==2){
                            exportSellerOrderListVO.setCommission(queryVO.getCommission().setScale(2, BigDecimal.ROUND_UP));
                        }
                    }
                    //预算佣金
                    // exportSellerOrderListVO.setCommission(queryVO.getCommission().setScale(2, BigDecimal.ROUND_UP));
                    if (orderStatVo.getPayState()!=null){
                        if (orderStatVo.getPayState()!=null){
                            if (orderStatVo.getPayState()!=2){
                                exportSellerOrderListVO.setEstimateCommission(new BigDecimal(0.00));

                            }
                            if (orderStatVo.getPayState()==2){
                                exportSellerOrderListVO.setEstimateCommission(queryVO.getEstimateCommission().setScale(2, BigDecimal.ROUND_UP));

                            }
                        }
                    }
                }
            }

           // exportSellerOrderListVO.setEstimateCommission(queryVO.getEstimateCommission().setScale(2, BigDecimal.ROUND_UP));
            exportSellerOrderListVO.setRefundAmount(queryVO.getRefundAmount().setScale(2, BigDecimal.ROUND_UP));

//            for(ExportSellerOrderListVO exportSellerOrderListVO1 : result){
//                if(exportSellerOrderListVO1.getOrderNumber().equals(exportSellerOrderListVO.getOrderNumber())){//如果有重复的就将该条重复数据预计技术服务费，实际技术服务器都设置为0.00
//                    exportSellerOrderListVO.setCommission(new BigDecimal(0.00));
//                    exportSellerOrderListVO.setEstimateCommission(new BigDecimal(0.00));
//                }
//            }
            if(result.contains(exportSellerOrderListVO)){
                exportSellerOrderListVO.setCommission(new BigDecimal(0.00));
                exportSellerOrderListVO.setEstimateCommission(new BigDecimal(0.00));
            }

            result.add(exportSellerOrderListVO);
        }
        return result;
    }

    /**
     * @return : java.lang.String
     * @Author :chenyu.wang
     * @Description : 获取订单状态
     * @Date : 2021.02.25 17:14
     * @Param : [state]
     **/
    private String getOrderState(Integer state) {
        // 订单状态 0待确定、1待签合同、2待付款、3待发货、4待签收、5已签收、6买家取消、7卖家已取消,20，异常订单（倒计时归0）
        String orderStatus = "暂无信息";
        switch (state) {
            case 0:
                orderStatus = "待确定";
                break;
            case 1:
                orderStatus = "待签合同";
                break;
            case 2:
                orderStatus = "待付款";
                break;
            case 3:
                orderStatus = "待发货";
                break;
            case 4:
                orderStatus = "待签收";
                break;
            case 5:
                orderStatus = "已签收";
                break;
            case 6:
                orderStatus = "买家取消";
                break;
            case 7:
                orderStatus = "卖家取消";
                break;
            default:
                break;
        }
        return orderStatus;
    }

    /**
     * @Description: 订单签收时根据订单id获取商品并更新es商品数据
     * @Author: chenyu.wang
     * @Params: [orderId]
     * @Date: 2020.11.20 09:47
     */
    public void updateEsGoods(Long orderId) {
        Wrapper<OrderCommodityRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        List<OrderCommodityRelationDTO> list = orderCommodityRelationService.selectList(wrapper);
        if (isNull(list)) {
            return;
        }
        for (OrderCommodityRelationDTO dto : list) {
            CommodityEsVO goods = commodityInfoService.queryESGoodsById(dto.getCommodityId());
            if (null == goods) {
                continue;
            }
            EsGoodsDTO esGoods = commodityInfoService.getEsGoods(goods).get(0);
            if (null == esGoods) {
                continue;
            }
            // 跟新es数据
            Boolean updateEntity = elasticsearchService.saveOrUpdateEntity(esGoods, "index_goods_2020", "goods", esGoods.getId().toString());
            if (!updateEntity) {
                log.info("订单更新es商品失败!");
            }
            log.info("订单更新es商品成功!");
        }
    }
}
